/*global Uwish, $ */
(function () {
    'use strict';
    Uwish._ = function (str) {return str; };

    /**
     * Statuses Class
     * @author Golban Sergiu
     */
    Uwish.Statuses = {
        AJAX_REDIRECT_LOGIN: -1
    };

    /**
     * Default ajax error handler
     * @author Golban Sergiu
     */
    $.ajaxSetup({
        error:function(request, status, err){
        	if (request.status != 500) {
        		return;
        	}
            var messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
            if(request.status == Uwish.Statuses.AJAX_REDIRECT_LOGIN) {
                messages.showMessage(Uwish._('Please Login to use this feature'), {delay: self.DELAY});
            } else {
                messages.showMessage(Uwish._('An unknown error occured, please try again later.'), {delay: self.DELAY});
            }
        }
    });
    
    /**
	 * Konstruktor klasy odpowiedzialnej za poprawne wy��wietlanie komunikat��w
	 * @property {Object} options
	 * @author Adam Sprada <sprada@red-sky.pl>
	 * @class
	 */
	Uwish.Messages = function(options) {
	    // opcje domy��lne
	    this.options = jQuery.extend({
	        id: 'messages_from_top',
	        idBody: 'messageBody',
	        idTab: 'messageTab',
	        idClose: 'closeMessage',
	        popup: 'popupError',
	        type : Uwish.Messages.TYPE.error,
	        position: 'top',
	        size: '67',
	        afterCall: null,     // callback po schowaniu komunikatu
	        leaveShown: null      // zostawia okno wiadomo��ci otwarte (zamykanie tylko na akcj�� u��ytkownika) 
	    }, options);
	    
	    this.settings = {
	        delay: 8000, // 8 sek. 
	        speed: 500
	    };
	    // przygotowanie szablonu html i umieszczenie go w body
	    this.prepareView();
	};
	
	/**
	 * Wy��wietlenie komunikatu
	 * @param {String} message
	 * @param {Object} settings
	 * @returns
	 */
	Uwish.Messages.prototype.showMessage = function(message, settings) {
		
	    // tre���� wiadomo��ci
	    this.message = message;
	    var popup = $('.' + this.options.popup);
	    var messageDiv = $('#' + this.options.id);
	    //hide popup before assigning of new message text
	    if (popup.is(':visible') &&  messageDiv.is(':visible')) {
	    	$('.' + this.options.popup).hide();
	    }
	    if (typeof(settings) !== 'undefined') {
	        // rozszerzenie domy��lnych opcji
	        this.settings = jQuery.extend(this.settings, settings);
	    }
	    
	    var self = this;
	    if (this.message.length != 0) { // pokazanie wiadomo��ci
	        this.element.find('#' + this.options.idBody).parent('div').addClass(this.options.type.popup);
	        this.element.find('#' + this.options.idBody).children('div').html(message);
	        this.element.find('#' + this.options.idTab).addClass(this.options.type.tab).text(Uwish._(this.options.type.name) );
	        
	        this.element.children().css(this.options.position, '-' + this.options.size + 'px');
	        
	        this.element.children().delay(200).show(function() {
	            var mHeight = self.element.find('#' + self.options.idBody).height();
	            var eHeight = self.element.find('#' + self.options.idBody + ' div').height();
	            var paddingTop = (mHeight-eHeight)/2;
	            self.element.find('#' + self.options.idBody).children().css({'padding-top':paddingTop+'px'}); // wy��rodkowanie tekstu w pionie
	        }).animate({
	            'top': '0'
	        }, this.settings.speed, function() {
	            if (!self.options.leaveShown) {
	                $(this).delay(self.settings.delay).animate({
	                    'top': '-' + self.options.size + 'px'
	                }, self.settings.speed, function() {
	                    // doda�� hide na popupError
	                    self.element.children().hide();
	                    // callback function
	                    if (self.options.afterCall !== null) {
	                        self.options.afterCall.call();
	                    }
	                });
	            }
	        });
	    }
	};
	
	/**
	 * Funkcja wywo��ywana po schowaniu komunikatu
	 * @param {Function} call_function
	 * @returns
	 */
	Uwish.Messages.prototype.setAfterCallback = function(call_function) {
	    this.options.afterCall = call_function;
	};
	
	/**
	 * Ustawia czy komunikat ma zosta�� czy si�� schowa�� po czasie delay
	 * @param {Boolean} leave
	 * @returns
	 */
	Uwish.Messages.prototype.setLeaveShown = function(leave) {
	    if (typeof(leave) === 'undefined') {
	        leave = null;
	    }
	    
	    this.options.leaveShown = leave;
	};
	
	/**
	 * Ustawia typ wiadomo��ci, w tej wersji zmienia kolor
	 * @param {Object} type     Messages.TYPE object
	 * @returns
	 */
	Uwish.Messages.prototype.setMessageType = function(type) { // type is a TYPE object
	    this.element.find('#' + this.options.idBody).parent('div').removeClass(this.options.type.popup).addClass(type.uwish);
	    this.element.find('#' + this.options.idTab).removeClass(this.options.type.tab).addClass(type.tab).text(Uwish._(type.name) );
	    
	    this.options.type = type;
	};
	
	/**
	 * Okno może posiadać zakładki, które będą posiadać tytuły
	 * @returns
	 */
	Uwish.Messages.prototype.prepareView = function() {
		$('.' + this.options.popup).stop(true, true).fadeOut('fast');
		this.element = $('#' + this.options.id);
	    this.element.show();
	    
	    if (this.element.length == 0) {
	        
	        // budowanie wygl��du wiadomo��ci
	        this.element = $('<div></div>')
	            .attr('id', this.options.id);
	        
	        this.element.append(
            $('<div></div>')
                .addClass('popupError')
                .append(
                $('<div></div>')
                    .addClass('popupContent')
                    .append(
                    $('<div></div>')
                        .addClass('popupMessage')
                        /*.addClass(this.options.type.popup)*/
                        .append(
	                        $('<div></div>')
	                            .addClass('popupMessageIco')
                        )
                        .append(
                            $('<div></div>')
                                .addClass('popupMessageText')
                                .attr('id', this.options.idBody)
                                .append($('<div></div>') )
                        )
                        .append(
                            $('<div></div>')
                                .addClass('popupMessageButtons')
                                .append(
                                        $('<img></img>')
                                            .attr('src', Uwish.Options.staticUrl + 'images/popupClose.gif')
                                            .attr('alt', 'close')
                                            .addClass('popupClose')
                                            .attr('id', 'closeMessage')
                                )
                                // opcjonalnie button
                                /*.append(
                                        $('<div></div>')
                                            .addClass('popupBlackBtn')
                                            .text()
                                )*/
                        )
                    )
                )
	        );
	        
	        // dodanie css (FIX: zIndex ustawiany jest z poziomu pliku css)
	        /*this.element.css({
	            'z-index': '999'
	        });*/
	        
	        // ukrycie elementu, ��eby nie by��o go wida�� w przypadku zwiechy przegl��darki po dodaniu do body
	        this.element.children().hide();
	        
	        var self = this;
	        // podpi��cie zdarzenia zamykania komuniaktu
	        this.element.find('#' + this.options.idClose).bind('click.messages', function() {
	            self.element.children().stop(); // this stop the currently-running animation
	            
	            self.element.children().animate({
	                'top': '-' + self.options.size + 'px'
	            }, self.settings.speed);
	        });
	        
	        // dodadnie do body
	        $('body').prepend(this.element);
	    }
	    
	};
	
	/**
	 * Typy wiadomo����i
	 * @property {Object}
	 */
	Uwish.Messages.TYPE = {
	        info : { popup: 'popupInfoMsg',
	                 tab : 'tabInfo',
	                 name : 'messages_info' },
	        error : {popup : 'popupErrorMsg',
	                 tab : 'tabError',
	                 name : 'messages_error' },
	        correct : { popup : 'popupOkMsg',
	                    tab : 'tabOk',
	                    name : 'messages_ok' }
	};

    /**
     * Favourite Class
     * 
     * @param {Boolean} isAdded Product is already added to wishlist or not
     * 
     * @author Golban Sergiu
     */
    Uwish.Wishlist = function (isAdded) {
        var 
        	/**
        	 * @param {Boolean} pending Synchronization variable to not to allow user
        	 * clicking more than once on button adding to wishlist.
        	 */
        	pending = false,
            BUTTON_SELECTOR = '.addWishlist';
        return {
        	/**
        	 * Adds item to currently logged user wishlist
        	 * @param {String} url Url of service
        	 * @returns
        	 */
        	add: function(url) {
        		var SUCCESS = 0,
		            DUPLICATED_PRODUCT_FAVOURITE = 2,
		            INVALID_FORMAT = 5;
        		
        		$(BUTTON_SELECTOR).click(function(event) {
        			if (pending || isAdded) {
        				return;
        			}
        			event.stopPropagation();
        			pending = true;
        			$.ajax({
        				url: url + '&format=json',
        				type: 'post',
        				dataType: 'json',
        				success: function(response) {
        					pending = false;
        					var messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
        					if (response.code == SUCCESS) {	
        						$(BUTTON_SELECTOR).text(Uwish._('Remove from wishlist'));
        						messages.showMessage(Uwish._('Product was added to your wishlist'), {delay: self.DELAY});
        						isAdded = true;
        					}
        					else if (response.code == DUPLICATED_PRODUCT_FAVOURITE) {
                                //already exist
                                messages.showMessage(Uwish._('You have already added this product to favourites'), {delay: self.DELAY});
                            }
                            else if (response.code == INVALID_FORMAT) {
                                //invalid data format or non-login
                                messages.showMessage(Uwish._('Invalid format or non-login'), {delay: self.DELAY});
                            }
        				},
        				error: function(request) {
        					pending = false;
        					if(request.status = Uwish.Statuses.AJAX_REDIRECT_LOGIN) {
                                messages.showMessage(Uwish._('Please Login to use this feature'), {delay: self.DELAY});
                            } else {
                                messages.showMessage(Uwish._('Failed to add to favourite'), {delay: self.DELAY});
                            }
        				}
        			});
        		});
        	},
        	remove: function(url) {
        		var SUCCESS = 0,
		            FAILED_TO_DELETE = 4,
		            INVALID_FORMAT = 5;
	            $(BUTTON_SELECTOR).click(function(event){
	            	if (pending || !isAdded) {
	            		return;
	            	}
	            	pending = true;
	            	event.stopPropagation();
                    var messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
                    $.ajax({
                        url: url + '&format=json',
                        type: 'post',
                        dataType: 'json',
                        success : function(response) {
                        	pending = false;
                            if (response.code == SUCCESS) {
                                $(BUTTON_SELECTOR).text(Uwish._('Add to wishlist'));
                                //$('.remove_favourite_js').attr('class', 'left add_favourite_js accConfirm');
                                messages.showMessage(Uwish._('Product was removed from your wishlist'), {delay: self.DELAY});
                                isAdded = false;
                            }
                            else if (response.code == FAILED_TO_DELETE) {
                                //already exist
                                messages.showMessage(Uwish._('Failed to delete product from list, please try again'), {delay: self.DELAY});
                            }
                            else if (response.code == INVALID_FORMAT) {
                                //invalid data format or non-login
                                messages.showMessage(Uwish._('Invalid format or non-login'), {delay: self.DELAY});
                            }
                            
                        },
                        error: function (request, status, error) {
                        	pending = false;
                            if(request.status = Uwish.Statuses.AJAX_REDIRECT_LOGIN) {
                                messages.showMessage(Uwish._('Please Login to use this feature'), {delay: self.DELAY});
                            } else {
                                messages.showMessage(Uwish._('Failed to delete product, please try again'), {delay: self.DELAY});
                            }
                            
                        }
                    });
	            });
        	}
        };
    };
    
    Uwish.Favourite = {
        addPending: false,
        communicates: {
        	shop: {'true': 'Store was added into your favourites list', 'false': 'Store was deleted from your favourites list' },
        	brand: {'true': 'Brand was added into your favourites list', 'false': 'Brand was deleted from your favourites list' }
        },
        favorShopOrBrand: function(ajaxUrl){
            var SUCCESS = 0,
            DUPLICATED_PRODUCT_FAVOURITE = 2,
            INVALID_FORMAT = 5;
            $('.favor_js').bind("click", function(){
                if (!Uwish.Favourite.addPending) {
                    Uwish.Favourite.addPending = true;
                    var self = this;
                    this.messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
                    $.ajax({
                        url: ajaxUrl + '?format=json',
                        type: 'post',
                        data: {'id' : self.value, 'type' : self.name},
                        dataType: 'json',
                        async: true,
                        success : function(response) {
                            if (response.code == SUCCESS) {
                                $(".favor_js[name='" + self.name + "']").checked = self.checked;
                                self.messages.showMessage(Uwish._(Uwish.Favourite.communicates[self.name][self.checked]), {delay: self.DELAY});
                            }
                            Uwish.Favourite.addPending = false;
                        },
                        error: function (request, status, error) {
                            self.messages.showMessage(Uwish._('Failed to change preferences'), {delay: self.DELAY});
                            self.checked = !self.checked;
                            Uwish.Favourite.addPending = false;
                        }
                    });
                }
            });
        }
    };
		
	/**
	 * Section  Class
	 * 
	 * @param {String} activeClass Active class name
	 * @param {String} inactiveClass Inactive class name
	 * @param {String} itemActive Active item
	 * @param {String} settings Flag for settings
	 * @author Alexandru Burlacu
	 */
	Uwish.Sections = function(activeClass, inactiveClass, itemActive, settings) {
		var priceSection = 'price',
			/**
			 * Expand sections items
			 * 
			 * @param {String} item Selected element id
			 * @author Alexandru Burlacu
			 */
			expandSection = function(item, checked) {
				
				//if seetings flag is true then we need always to expand this section
				if(settings || checked == 'checked') {
					$(item).parent().removeClass(inactiveClass)
					.addClass(activeClass);
				}else if ($(item).parent().hasClass(activeClass)) {
					$(item).parent().removeClass(activeClass).addClass(
							inactiveClass);
				} else {
					$(item).parent().find(itemActive).removeClass(
							activeClass).addClass(inactiveClass);
					$(item).parent().removeClass(inactiveClass)
					.addClass(activeClass);
				}
			};
	
		
			/**
			 * Open Close section items
			 * 
			 * @param {String} selector Selected section
			 * @param {String} checked Checked values
			 * @param {String} idPrefix Id of expanded item
			 * @author Alexandru Burlacu
			 */
			this.viewSections = function(selector, checked, idPrefix) {
				checked = idPrefix != priceSection ? checked.split (',') : checked;
				if(checked == 'checked'){
					expandSection('#'+idPrefix, checked);
				} 
				else if (idPrefix == 'group'){				
					for (var n = 0; n < checked.length; n++){
						expandSection('#'+idPrefix+checked[n], checked);
					}
				}
				else if (idPrefix == priceSection && checked.length > 1){				
						expandSection(selector);
				}
				$(selector).click(
						function() {
							expandSection(this);
						});
			};
	};
	
	/**
	 * Filters Class
	 * 
	 * @author Alexandru Burlacu
	 */
	Uwish.Filters = (function() {
		//public interface
		return function (activeClass, inactiveClass, itemActive){
			//Section management
			this.viewSections = function(selector, checkedItems, idPrefix, settings) {
				 var sections = new Uwish.Sections(activeClass, inactiveClass, itemActive, settings); // new instance of class Sections
		   	     sections.viewSections(selector, checkedItems, idPrefix);
			},
			
			/**
			 * Uncheck all checkboxes
			 * 
			 * @param {String} selector Selection of clear item
			 * @param {String} allClass Class name of all affected checkboxes
			 * @author Alexandru Burlacu
			 */
			this.unCheckAll = function(selector, allClass) { 
				$(selector).click(function() {
					$('input:checkbox.' + allClass).attr('checked', false);
				});
			},
			
		    
			/**
			 * Select all checkboxes by parent category
			 * 
			 * @param {String} selector Selected checkbox
			 * @param {String} group Group name of checkboxes that belong to parent category
			 * @author Alexandru Burlacu
			 */
			this.checkAllByParent = function(selector, group) { 
				$(selector).click(function() {
					$(this).parent().find("input[type='checkbox']").attr('checked', $(this).attr('checked'));
				});
			};
			
			/**
			 * Price filters validation
			 * 
			 * @param {String} selector Selected checkbox
			 * @author Alexandru Burlacu
			 */
			this.priceValidation = function (selector) {
			    $(selector).keypress(function (event) {
			        // Backspace, tab, enter, end, home, left, right
			        var controlKeys = [8, 9, 13, 35, 36, 37, 39],
			            isControlKey = controlKeys.indexOf(event.which),
			            isDot = $(this).val().indexOf('.');
			        // Always 1 through 9,  No 0 first digit, allow only one dot
			        if (!event.which || (49 <= event.which && event.which <= 57) || (48 == event.which && $(this).attr("value")) || isControlKey > -1 || (event.which == 46 && isDot == -1 )) {
			            return;
			        } else {
			            event.preventDefault();
			        }
		        });
		    };
	    };
    })();
	
	/**
	 * Switch Tabs
	 * 
	 * @param {String} selector Selected tab
	 * @param {String} activeClass Active class name
	 * @param {String} itemActive  Active item
	 * @param {String} displayedItem Displayed item
	 * @param {String} displayedTab  Displayed tab
	 * @return 
	 * @author Alexandru Burlacu
	 */
	Uwish.Tabs = (function(options) {
		return function(selector, activeClass, itemActive, displayedItem,
				displayedTab) {
			$(selector).click(function() {
				$(this).parent().find(itemActive).removeClass(activeClass);
				$(this).addClass(activeClass);
				var tabNumber = $(this).attr("id");
				$(displayedItem).hide();
				$(displayedTab).find("#" + tabNumber).show();
			});
		};
	})();
	
	
	
	/**
	 * Rating Class
	 * 
	 * @author Alexandru Burlacu
	 */
	Uwish.Rating = (function(){
		var AJAX_LOADER_ICON = Uwish.Options.staticUrl + '/images/ajax-loader.gif',
			SUCCESS = 0, 
			//user is not active
			NOT_ACTIVE_USER = 1, 
			//user already added comment for this item
			COMMENTS_ALREADY_ADDED = 2,
			//user is not logged in
			NOT_LOGGED_USER = 3,
			//user doesn't have nickname yet
			MISSING_NICKNAME = 4,
			//unpredictable db error for comment inserting 
			INSERT_COMMENT_UNPREDICTABLE_ERROR = 2,
			//the comment length exceeded the maximum limit
			COMMENT_LENGTH_EXCEEDED = 6,
			//the comment is empty
			COMMENT_IS_EMPTY = 7,
			COMMENT_LIMIT_INSERT = 5000,
			dialogControls = 'dialogControls',
			dialogClass = 'dialog',
			errorClass = 'errors';
			
		//public interface
		return function (productSubmit){
			var	selectReviewTab = function(obj,activeClass,reviewsClass) {
				$(obj).parent().find("." + activeClass).removeClass(activeClass);
				$(obj).addClass(activeClass);
				var boxName = $(obj).attr("id");
				$(obj).parent().parent().find("."+reviewsClass).hide();
				$("."+boxName).show();
			};
		
			/**
			 * Rating Reviews
			 * @param {String} selector Selected Tabs
			 * @param {String} activeClass Active class name
			 * @param {String} reviewsClass Review class
			 * @author Alexandru Burlacu
			 */
			this.ratingReview = function (selector, currentRating) { 
				$(selector).click(function () {
					$('#'+currentRating).width($(this).width());
					$('#selectedVoteProduct').val($(this).attr('id'));
					$('#selectedVoteShop').val($(this).attr('id'));
				});
			};
			
			
			/**
			 * Select Review
			 * @param {String} selector Selected Tabs
			 * @param {String} activeClass Active class name
			 * @param {String} reviewsClass Review class
			 * @author Alexandru Burlacu
			 */
			this.reviewTabs = function (selector,activeClass,reviewsClass,selectedTab) {
				//Select Default tab
				selectReviewTab($('#'+selectedTab).val(), activeClass,reviewsClass);
				//Switch tab
				$(selector).click(function() {
					selectReviewTab(this, activeClass,reviewsClass);
					
				});
			};
			
			/**
			 * Create dialog
			 * @author Alexandru Burlacu
			 */
			var openDialog = function () { 
				$('#dialog').dialog({
				title: Uwish._("Add Comment"),
				height: 235,
				width: 450,
				modal: true,
				resizable: false 
				});
			};
			/**
			 * Rating Reviews
			 * @param {String} selector Selected Tabs
			 * @param {String} activeClass Active class name
			 * @param {String} reviewsClass Review class
			 * @author Alexandru Burlacu
			 */
			var ratingReviewDialog = function (selector) {
				$(selector).click(function () {
					$('#currentProductRating').width($(this).width());
					$('#selectedVoteProduct').val($(this).attr('id'));
					$('.ui-dialog').empty().remove();
					openDialog();
				});
			};

			/**
			 * InsertComment
			 * @param {String} selector Selected Tabs
			 * @param {String} product fullId
			 * @author Alexandru Burlacu
			 */
			var insertComment =  function (selector, fullId) {
				$(selector).click(function () {
					var vote = $('#selectedVoteProduct').val(),
						comment = $('#productCommentArea').val();
					$('.' + errorClass).hide();
					$('#' + dialogControls).hide();
					
					// this is where we append a loading image
					$('#ajax-panel').html('<div id="loading"><img src=' + AJAX_LOADER_ICON + ' /></div>');
					$.ajax({
						url: Uwish.Options.baseUrl + "/insert-product-rating.html",
						data: {'fullId' : fullId, 'vote' : vote, 'comment' : comment},
						type: 'post',
						dataType: 'json',
						async: true,
						success : function (response) {
							$('#loading').animate({opacity: 0}, 1000, 'linear', function () {
								$('#' + dialogControls).show();
								$(this).remove();
								if (response.code === SUCCESS) {
									$('#' + errorClass).show();
									$('#' + dialogClass).dialog('option', 'title', Uwish._("Information"));
									$('#successDisplaying').show();
									$(selector).attr('disabled', 'false');
									$('#productCommentArea').attr('disabled', 'false');
								} else if (response.code === INSERT_COMMENT_UNPREDICTABLE_ERROR) { //dont check code 1  for duplication, it was checked on displaying dialog
									$('#' + dialogClass).dialog('option', 'title', Uwish._("Error Notification"));
									$('#' + errorClass).show();
									$('#errorAddingCode2').show();
								} else if (response.code === COMMENT_LENGTH_EXCEEDED) {
									$('#' + dialogClass).dialog('option', 'title', Uwish._("Error Notification"));
									$('#' + errorClass).show();
									$('#errorAddingCode3').show();
								} else if (response.code === COMMENT_IS_EMPTY) {
									$('#' + dialogClass).dialog('option', 'title', Uwish._("Error Notification"));
									$('#' + errorClass).show();
									$('#errorAddingCode4').show();
								}
							});
							if (response.code === SUCCESS) {
								//update rates in search results
								$.ajax({
									url: Uwish.Options.baseUrl + "/get-product-details.html",
									data: {'fullId' : fullId },
									type: 'post',
									dataType: 'json',
									async: true,
									success : function (response) {
										if (response.code === SUCCESS) {
											var avgRate = "(" + response.results.avgRate + ")",
												custReview = "(" + response.results.custReview + ")",
												vote = response.results.ratingClass;
											//Update exact record from search results
											$('#ratingNumber' + fullId).text(avgRate);
											$('#ratingCust' + fullId).text(custReview);
											$('#ratingStars' + fullId).attr('class','ratingStars ' + vote);
										}
									}
								});
							}
						},
						error : function (request,err) {
							$('#loading').animate({opacity: 0}, 1000, 'linear', function () {
								$('#' + dialogClass).dialog('option', 'title', Uwish._("Error")); 
								$('#' + errorClass).show();
								$('#' + errorClass).html('<span id="errorSpan">' + err + '</span>');
							});
						}
					});
				});
			};
			
			/**
			 * Open Dialog
			 * @param {String} selector Selected Tabs
			 * @author Alexandru Burlacu
			 */
			this.dialog = function (selector) {
				ratingReviewDialog(".star-rating a");
				$(selector).click(function () {
					var div = $(this).attr('id'),
						fullId = div.replace('rating', '');
					insertComment('#addProductReview', fullId);
					$('.errors').css({display: "none"});
					$('#dialogControls').css({display: "none"});
					openDialog();
					$('#ajax-panel').html('<div id="loading"><img src=' + AJAX_LOADER_ICON + ' /></div>');
					$.ajax({
						url: Uwish.Options.baseUrl + "/search.html",
						data: {'fullId' : fullId, format : 'json'},
						type: 'post',
						dataType: 'json',
						async: true,
						success : function (response) {
							$('#loading').animate({opacity: 0}, 1000, 'linear', function () {
								$(this).remove();
								if (response.code === SUCCESS) {
									$('#dialogControls').show();
								} else if (response.code === NOT_ACTIVE_USER) {
									$('#dialog').dialog('option', 'title', Uwish._("Warning"));
									$('#errors').show();
									$('#errorDisplayingCode1').show();
								} else if (response.code === COMMENTS_ALREADY_ADDED) {
									$('#dialog').dialog('option', 'title', Uwish._("Warning")); 
									$('#errors').show();
									$('#errorDisplayingCode2').show();
								} else if (response.code === NOT_LOGGED_USER) {
									$('#dialog').dialog('option', 'title', Uwish._("Warning")); 
									$('#errors').show();
									$('#errorDisplayingCode3').show();
								} else if (response.code === MISSING_NICKNAME) {
									$('#dialog').dialog('option', 'title', Uwish._("Warning")); 
									$('#errors').show();
									$('#errorDisplayingCode4').show();
								}
							});
						},
						error : function (request,err) {
							$('#loading').animate({opacity: 0}, 1000, 'linear', function () {
								$('#dialog').dialog('option', 'title', Uwish._("Error")); 
								$('#errors').show();
								$("#errors").html('<span id="errorSpan">' + err + '</span>');
							});
						}
					});
				});
			};
			/**
			 * Jquery counter
			 * @param {String} selector Selected Tabs
			 * @param {String} id of counter
			 * @author Alexandru Burlacu
			 */
			this.countable = function (selector, counter) {
				$(selector).simplyCountable({
					counter: '#' + counter,
					countType: 'characters',
					maxCount: COMMENT_LIMIT_INSERT,
					countDirection: 'down',
					onOverCount: function () {
						$('#' + productSubmit).attr("disabled", true);
					},
					onSafeCount: function () {
						$('#' + productSubmit).attr("disabled", false);
					}
				});
			};
		};
	})();
	
	/**
	 * Klasa zarz��dzaj��ca po����czeniami z Facebookiem
	 * @param {String} appId
	 * @author Adam Sprada <sprada@red-sky.pl>
	 * @constructor
	 */
	Uwish.Facebook = function(appId) {
	    $('body').append($('<div></div>').attr('id', 'fb-root') );
	    
	    this.DELAY = 6000; // 6 sek.
	    this.appId = appId;
	    this.messages = null;
	    this.init();
	};
	
	/**
	 * Inicjalizacja Api facebooka
	 * @returns
	 */
	Uwish.Facebook.prototype.init = function() {
	    var self = this;
	    window.fbAsyncInit = function() {
	        FB.init({appId: self.appId, status: true, cookie: true, xfbml: true, oauth: true});
	        FB.getLoginStatus(function(response) {
	            if (response.authResponse) {
	                // logged in and connected user, someone you know
	                if (!Uwish.Options.logged || (Uwish.Options.logged && !Uwish.Options.connected) ) {
	                    // prze��adowanie strony || wy��wietlenie account_box
	                    FB.api('/me', function(response) {
	                        // ajax request
	                        var me = {'id' : response.id,
	                                  'email' : response.email,
	                                  'name' : response.name };
	                        // wys��anie ����dania o utworzenie konta lub zalogowanie
	                        self.connect(me);
	                    });
	                }
	            }
	            else {
	                // no user session available, someone you dont know'
	            }
	        });
	        FB.Event.subscribe('auth.login', function(response) {
	            // do something with response
	            self.reloadPage();
	        });
	    };
	    (function() {
	        var e = document.createElement('script'); e.async = true;
	        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	        document.getElementById('fb-root').appendChild(e);
	    }());
	};
	
	/**
	 * Logowanie/tworzenie konta po akceptacji aplikacji na FB
	 * @param {Object} me
	 * @returns
	 */
    Uwish.Facebook.prototype.connect = function(me) {
        var self = this,
        OK = 0,
        ERROR = 1,
        ERROR_FB_CONNECTED = 4,
        OK_FB_ACCOUNT_CREATE = 7,
        OK_FB_CONNECTED = 8;
        this.messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
        $.ajax({
            url: Uwish.Options.baseUrl + "/facebook/connect",
            data: {'userData' : me},
            type: 'post',
            dataType: 'json',
            async: true,
            success : function(response) {
                // je��eli by�� niezalogowany to trzeba pokaza�� box za awatarem i ukry�� menu z logowaniem|rejestracj�� (reload page)
                // response.code == 0 OK
                // response.code == 1 ERROR DB
                // response.code == 4 ERROR Inne konto w Uwish.com ju�� powi��zane z tym u��ytkownikiem serwisu Facebook
                // response.code == 7 OK FB CREATED Stworzone zosta��o nowe konto
                // response.code == 8 OK FB CONNECTED Istniej��ce konto powi��zane
                if (response.code == ERROR_FB_CONNECTED) {
                    FB.logout(function(response) {
                        // show message to user and
                        // user is now logged out
                        self.messages.setMessageType(Uwish.Messages.TYPE.error);
                        self.messages.showMessage(Uwish._('Your Facebook account has already been linked with another account in Uwish!') );
                    });
                }
                else if (response.code == OK) {
                    // show message, login success
                    self.messages.showMessage(Uwish._("Logging in through Facebook has been successful!"), {delay: self.DELAY});
                    self.messages.setAfterCallback(self.reloadPage);
                }
                else if (response.code == OK_FB_ACCOUNT_CREATE) {
                    // show message, login success
                    self.messages.showMessage(Uwish._("Register through Facebook has been successful!"), {delay: self.DELAY});
                    self.messages.setAfterCallback(self.reloadPage);
                }
                else if (response.code == OK_FB_CONNECTED) {
                    // show message, create account success
                    self.messages.showMessage(Uwish._("Linking your account with Facebook has been successful! You can now use all of Uwish.com's features. Enjoy!"), {delay: self.DELAY});
                    self.messages.setAfterCallback(self.reloadPage);
                }
                else if (response.code == ERROR) {
                    // show message, connect success
                    self.messages.showMessage(Uwish._('An error occured while trying to connect with Facebook. Please try again later.'), {delay: self.DELAY});
                    // self.messages.setAfterCallback(self.reloadPage);
                }
            }
        });
    };
	
	/**
	 * Prze��adowanie bie����cej strony w celu od��wie��enia parametr��w po zalogowaniu
	 * @returns
	 */
	Uwish.Facebook.prototype.reloadPage = function() {
	    window.location.reload(true);
	};    		
	
	
	
	//Open Close category items
	var CategoryManager = (function(){
		return function(selector, activeClass, inactiveClass, itemActive) {
			$(selector).click(function(){
				  if($(this).parent().hasClass(activeClass)){
					 $(this).parent().removeClass(activeClass).addClass(inactiveClass);
				  }
			      else{
			    	  	$(this).parent().find(itemActive).removeClass(activeClass).addClass(inactiveClass);
			    	  	$(this).parent().removeClass(inactiveClass).addClass(activeClass);
					 }
			});
		 };
	})();
	
	//Switch Tabs
	var Tabs = (function(){
		return function(selector, activeClass,  itemActive, displayedItem, displayedTab) {
			$(selector).click(function(){
				$(this).parent().find(itemActive).removeClass(activeClass);
				$(this).addClass(activeClass);
				var tabNumber = $(this).attr("id");
			    $(displayedItem).hide();
			    $(displayedTab).find("#"+tabNumber).show(); 
			});
		};
	})();
	
	Uwish.logout = function() {	
	   $('#logout').bind('click.logout', function(event) {
		   event.preventDefault();
	       // logout from fb is connected
	       try {
	           FB.getLoginStatus(function(response) {
	               if (response.authResponse) {
	                   FB.logout(function() {
	                       // user is now logged out
	                       // now logout from Uwish
	                       window.location.href = '/account/logout';
	                   });
	               }
	               else {
	                   window.location.href = '/account/logout';
	               }
	           });
	       }
	       catch (e) {
	           window.location.href = '/account/logout';
	       }
	   });   
	};
	
	
	
	/**
	 * Search Results View Class
	 * 
	 * @author Alexandru Burlacu
	 */
	Uwish.SearchResultsView = (function () {
		var defaultOptions = {
			 //Expired days
			'expiredDays': 2,
			'today' : new Date(),
			//Name of cookie {Uwish_Model_Cookies}
			'cookieName' : 'searchResultsView',
			//Box icon image
			'boxImg' : ".viewChanger span.boxView img",
			//List icon image
			'listImg' : ".viewChanger span.listView img",
			//Div for list View
			'lView' : "searchResultsList",
			//Div for box view
	        'bView' : "searchResultsBox"
		},
		//Expired date
		expiredDate = '',
		//Set images urls
		ACTIVE_LIST_ICON = Uwish.Options.staticUrl + '/images/viewListAct.gif', 
		ACTIVE_BOX_ICON = Uwish.Options.staticUrl + '/images/viewBoxAct.gif',
		INACTIVE_LIST_ICON = Uwish.Options.staticUrl + '/images/viewListIn.gif',
		INACTIVE_BOX_ICON = Uwish.Options.staticUrl + '/images/viewBoxIn.gif',
                BOX_PRODUCT_NAME_SIZE = 45,
		LIST_PRODUCT_NAME_SIZE = 130,
		MAX_PATH_SIZE_BOX = 45,
		MAX_PATH_SIZE_LIST = 150,
		PRICE_LENGTH = 7;
	    /**
	      *  Constructor params
	      * 
	      * @param {String} cookieView Current search results view from Cookie
	      * @data {Array} data Array of products
	      * @author Alexandru Burlacu
	     */	

	    return function (cookieView, dataArray, forEdit) {
	        //private region
	        var options = $.extend(defaultOptions, options || {}),
	            vote = "",
	            div = "",
	            data = dataArray,
	            i = 0,
	            cookieValue = "",
            /**
		      * Generate search Results
		      * 
		      * @param {Object} element The main html element that will contain the search results
		      * @author Alexandru Burlacu
		      */
	        generateSearchResults = function (element, productNameSize, type) {
        	    for (i = 0; i < data.length; i = i + 1) {
                    vote = Math.round(data[i].avgRate);
                    switch (vote) {
                    case 0: vote = "zeroStars"; break;
                    case 1: vote = "oneStar";  break;
                    case 2: vote = "twoStars"; break;
                    case 3: vote = "threeStars"; break;
                    case 4: vote = "fourStars"; break;
                    case 5: vote = "fiveStars"; break;
                    default: vote = "zeroStars"; break;
                    }
                    var productName = Uwish.truncate(data[i].productName, productNameSize),
                        thumbUrl = type == options.lView ? data[i].listThumb : data[i].boxThumb,
                        thumb =  thumbUrl ? thumbUrl : Uwish.Options.staticUrl + '/images/noimage_110x100.png',
                        price = data[i].price.length > PRICE_LENGTH && type == options.lView ? data[i].price.substr(0, PRICE_LENGTH) + "..." : data[i].price,
                        categoryPath = data[i].categoryPath;
                        categoryPath = type == options.bView ? Uwish.truncateBreadcrumbs(categoryPath, MAX_PATH_SIZE_BOX) : Uwish.truncateBreadcrumbs(categoryPath, MAX_PATH_SIZE_LIST);
                        var resultItem = $('<div></div>')
                            .attr('id', 'searchResultItem')
                            .addClass('searchResultItem')
                            .append(
                                $('<div></div>')
                                    .addClass('searchResultItemPhoto')
                                    .append(
                                    	$('<a></a>')
                                    		.attr('href', data[i].href)
		                                    .append(
		                                    	$('<img></img>')
		                                        	.addClass('resize_horizontal')
		                                        	.addClass('lazy')
		                                        	.attr('data-href', thumb)
		                                        	.attr('alt', '')
		                                    )
                                    )
                            )
                            .append($('<div></div>')
                                .addClass('searchResultItemDescription')
                                .append(
                                    $('<span></span>')
                                        .addClass('searchResultItemDescriptionName')
                                        .append(
                                            $('<a></a>')
                                                .addClass('searchResultItemDescriptionName')
                                                .attr('id', 'product' + data[i].productId)
                                                .attr('href', data[i].href)
                                                .attr('name', '')
                                                .text(productName)
                                        )
                                )
                                .append(
                                    $('<div></div>')
                                        .append(
                                            $('<span></span>')
                                                  .addClass('searchResultItemDescriptionCategory')
                                                  .attr('title', data[i].categoryPath.join('>>'))
                                                  .text(categoryPath)
                                        )
                                )
                                )
                              .append(
                                $('<div></div>')
                                    .addClass('searchResultItemPrice')
                                    .append(
                                        $('<span>$</span>')
                                              .addClass('currency')
                                    )
                                    .append(
                                        $('<span></span>')
                                            .addClass('price')
                                            .attr('title', data[i].price)
                                            .text(price)
                                    )
                            ),
                            elementOption =  $('<div></div>')
                                    .addClass('searchResultItemOptions')
                                    .append(
                                        $('<div></div>')
                                            .addClass('itemAverageRating')
                                            .append(
                                                $('<span>' + Uwish._("Average rating") + '</span>')
                                                    .addClass('gray')
                                            )
                                            .append(
                                            		$('<span></span>')
                                            			.addClass('ratingStars ' + vote)
                                            )
                                            .append(
                                            		$('<span></span>')
                                            			.addClass('ratingNumber')
                                            			.text("(" + data[i].avgRate + ")")
                                            )
	                                    .append(
	                                        $('<div></div>')
	                                             .addClass('itemAverageRating')
	                                             .append(
	                                                $('<span>' + Uwish._("Customer reviews") + '</span>')
	                                                    .addClass('gray')
	                                            )
	                                            .append(
	                                                $('<span></span>')
	                                                    .addClass('ratingNumber')
	                                                    .text("(" + data[i].custReview + ")")
	                                            )
	                                    )
                                    );
                    if(forEdit) {
                        var remove = $('<a></a>')
                             .addClass('left remove_favourite_js accConfirm')
                             .attr('name', 'product' + data[i].fullId)
                             .text(Uwish._('Remove'));
                        elementOption.append(remove);
                    }
                    resultItem.append(elementOption);
                    element.append(resultItem);
                }
            },
            /**
		      * Generate results in selected view 
		      * 
		      * @param  {String} type Type of class
		      * @author Alexandru Burlacu
		      */
	        generateSearchResultsView = function (type) {
            	var productNameSize = type == options.lView ? LIST_PRODUCT_NAME_SIZE : BOX_PRODUCT_NAME_SIZE;
                div = $('<div></div>').addClass(type);
                generateSearchResults(div, productNameSize, type);
                //Add search results to view
                $('#searchResultsItemsDiv').empty();
                $('#searchResultsItemsDiv').append(div);
            },
	
	            

	        /**
		      * Show current view
		      * 
		      * @param {String} activeImg Active Image
		      * @param {String} inactiveImg Inactive Image
		      * @param {String} activeIcon Active icon
		      * @param {String} inactiveIcon Inactive icon
		      * @param {String} type Type of class
		      * @author Alexandru Burlacu
		      */
            showCurrentView = function (activeImg, inactiveImg, activeIcon, inactiveIcon, type) {
                $(activeImg).attr("src", activeIcon);
                $(inactiveImg).attr("src", inactiveIcon);
                //generate new search reults view
                generateSearchResultsView(type);
                //unbind scroll event is needed, because asyncImageLoader will try to load images from unexisting view 
            	$(window).unbind('scroll');
            };
            
            /**
             * Deletes product from in-memory products list. This
             * does not delete product from DOM!
             * 
             * @param {Number} productId Id of product which should be deleted
             */
            var deleteProduct = function(productId) {
            	for (var i = 0; i < data.length; i = i + 1) {
                    if(data[i].fullId == productId) {
                        data.splice(i, 1);
                        return;
                    }
                }
            };
	            
            /**
              * Delete an object from list
              * 
              * @param {Int} productId
              * @author Golban Sergiu
              */
            this.deleteFromList = function () {
            var SUCCESS = 0,
	            FAILED_TO_DELETE = 4,
	            INVALID_FORMAT = 5,
	            deletePending = false;
            $('.remove_favourite_js').live("click", function(){
                if (!deletePending) {
                    deletePending = true;
                    var self = this,
                        productId = $(this).attr('name').replace("product", ""),
                        ajaxUrl = Uwish.Options.baseUrl + '/delete-from-favourites.html?fullId=' + productId;
                    this.messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
                    $.ajax({
                        url: ajaxUrl + '&format=json',
                        type: 'post',
                        dataType: 'json',
                        async: true,
                        success : function(response) {
                            if (response.code == SUCCESS) {
                                $(self).parent().parent().remove();
                                //Remove deleted product from product array
                                deleteProduct(productId);
                                
                                self.messages.showMessage(Uwish._('Removed from favourites'), {delay: self.DELAY});
                            }
                            else if (response.code == FAILED_TO_DELETE) {
                                //already exist
                                self.messages.showMessage(Uwish._('Failed to delete product from list, please try again'), {delay: self.DELAY});
                            }
                            else if (response.code == INVALID_FORMAT) {
                                //invalid data format or non-login
                                self.messages.showMessage(Uwish._('Invalid format or non-login'), {delay: self.DELAY});
                            }
                            deletePending = false;
                        },
                        error: function (request, status, error) {
                            self.messages.showMessage(Uwish._('Failed to delete product, please try again'), {delay: self.DELAY});
                            deletePending = false;
                        }
                    });
                }
            });

            };
	          //public region
	          /**
	           *
	           * Display search results
	           *
	           * @param {String} selector Selected tab
	           */
	        this.displayResults = function (selector) {
	        	
	        	//check if cookie value is empty is empty
	            cookieView = cookieView === '' ? options.lView : cookieView;
	            if (cookieView === options.bView) {
	                $(options.boxImg).attr("src", ACTIVE_BOX_ICON);
	                $(options.listImg).attr("src", INACTIVE_LIST_ICON);
	            }
	            if (cookieView === options.lView) {
	                $(options.listImg).attr("src", ACTIVE_LIST_ICON);
	                $(options.BoxImg).attr("src", INACTIVE_BOX_ICON);
	            }
	            options.today.setTime(options.today.getTime());
	            expiredDate = new Date(options.today.getTime() + (1000 * 60 * 60 * 24 * options.expiredDays));
	            $(selector).click(function () {
	                if ($(this).hasClass("boxView")) {
	                    showCurrentView(options.boxImg, options.listImg, ACTIVE_BOX_ICON, INACTIVE_LIST_ICON, options.bView);
	                    cookieValue = options.bView + ((options.expiredDays === null) ? "" : "; expires=" + expiredDate);
	                }
	                if ($(this).hasClass("listView")) {
	                    showCurrentView(options.listImg, options.boxImg, ACTIVE_LIST_ICON, INACTIVE_BOX_ICON, options.lView);
	                    cookieValue = options.lView + ((options.expiredDays === null) ? "" : "; expires=" + expiredDate);
	                }
	                document.cookie = options.cookieName + " = " + cookieValue;
	                $('img.lazy').jail({
	                    effect: 'fadeIn',
	                    speed: 500
	                });	
	            });
	        };
	    };
	})();

    /**
     * Post ContactUs and your opinion form using ajax
     * 
     * @param  {String} ajaxUrl - url for form action
     * @param  {Boolean} limitedValidation - if it's true than validate your opinion form, false for contactUs form
     * @author Alexandru Burlacu
     */
	Uwish.postAjaxForm = function (ajaxUrl, limitedValidation) {
		var pending = false,
			AJAX_LOADER_ICON = Uwish.Options.staticUrl + '/images/ajax-loader.gif';
		$('#submitContactUs').click(function () {
		    if (pending) {
		    	return;
		    }
            var SUCCESS = 0,
                ERROR = 1,
                self = this,
                formData = {},
                errorClass = "errorMessage";
            this.messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
		    if ((formData.messagetype = $('#messageType').val()) && (formData.email = $('#email').val()) && (formData.message = $('#message').val()) || (limitedValidation && (formData.message = $('#message').val()))) {
		    	$('.' + errorClass).remove();
			    pending = true;
			    $('#ajax-panel').html('<div id="loading"><img src=' + AJAX_LOADER_ICON + ' /></div>');
			    $.ajax({
				    url: ajaxUrl + '?format=json',
				    type: 'post',
				    data: {'messageType' : formData.messagetype, 'email' : formData.email, 'message' : formData.message},
				    dataType: 'json',
				    async: true,
				    success : function (response) {
					    $('#loading').animate({opacity: 0}, 1000, 'linear', function () {
					    	$('#ajax-panel').empty();
						    if (response.code === SUCCESS) {
						        if (limitedValidation) {
						            self.messages.showMessage(Uwish._('Thank you very much for your opinion'), {delay: self.DELAY});
						        } else {
						            self.messages.showMessage(Uwish._('Thank you very much for your comunication'), {delay: self.DELAY});
						        }
						    } else if (response.code === ERROR) {
							    //invalid data format or non-login
							    self.messages.showMessage(Uwish._('Please try again, the email format you provided is wrong'), {delay: self.DELAY});
						    }
					    });
					    pending = false;
				    },
				    error: function (request, status, error) {
					    $('#loading').animate({opacity: 0}, 1000, 'linear', function () {
					    	$('#ajax-panel').empty();
						    pending = false;
					    });
				    }
			    });
		    } else {
		    	$('#ajax-panel').empty();
		    	if (!$('.' + errorClass)[0]){
		    		$('.formContainer').append('<p class="' + errorClass + '">' + Uwish._("All fields are required!") + '</p>');
		    	}
		    }
		});
	};
	/**
	 * Jquery show nore or less text
	 * @param {String} selector Selected Tabs
	 * @param {String} type of text
	 * @param {Object} values Values(prodComments, shopComments or productDescription)
	 * @param {integer} limit Characters limit
	 * @author Alexandru Burlacu
	 */
	Uwish.showMoreLess = function (selector, values, limit ) {
		var isMore = true,
			type = $(selector).attr('class'),
			options = {
				'moreLink' :  'more',
				'lessLink' :  'less',
				'rightArrow' : '&raquo;',
				'leftArrow' : '&laquo;'
		};
		$(selector).click(function () {
			var id = $(this).attr('id');
			id = id.replace(type, '');
			if (id > 0) {
				var fullText = typeof(values) == 'object' ? values[id].comment : values,
					//truncate text if limit is exceeded	
					text = Uwish.truncate(fullText, limit),
					//display other link  name after clicking
					textLink = isMore ? options.lessLink : options.moreLink,
					//display rigthArrow or leftArrow
					rightArrow = isMore ? '' : options.rightArrow,
					leftArrow = isMore ? options.leftArrow : '';
				//display full text if user clicked 'more' link	
				text = isMore ? fullText : text;
				$('#' + type + id).text("");
				$('#' + type + id)
					.append(
						$("<p></p>")
							.text(text)
					);
				$(this).attr('name', textLink);
				//display appropriate translated link and arrows
				$(this).html('<span>' + leftArrow + Uwish._(textLink) + rightArrow +'</span>');
				//change the status of clicked link
				isMore = isMore ? false : true;
			}
		});
	};

	   /**
     * Jquery show more or less block
     * @param {String} selector Selected Tabs
     * @author Golban Sergiu
     */
	   Uwish.showMoreLessFavourites = function (selector) {
	        var isMore = true,
	           options = {
	                'moreLink' :  'more',
	                'lessLink' :  'less',
	                'rightArrow' : '&raquo;',
	                'leftArrow' : '&laquo;'
	            };
	        $(selector).click(function () {
                var textLink = isMore ? options.lessLink : options.moreLink,
                    //display rigthArrow or leftArrow
                    rightArrow = isMore ? '' : options.rightArrow,
                    leftArrow = isMore ? options.leftArrow : '',
                    className = $(this).attr('class');
                isMore ? $('#' + className).show() : $('#' + className).hide();
                $(this).attr('name', textLink);
                //display appropriate translated link and arrows
                $(this).html('<span>' + leftArrow + Uwish._(textLink) + rightArrow +'</span>');
                //change the status of clicked link
                isMore = isMore ? false : true;
	        });
	    };

	/**
	 * Autocompleter class.
	 * @todo Klasa pisana do���� na szybko, z minimalnymi usprawnieniami w stosunku
	 * do pierwowzoru, przyda��oby si�� przepisa�� j�� od pocz��tku do ko��ca
	 * 
	 * @author Piotr Deszynski
	 */
	Uwish.Autocompleter = (function() {
	    var ac_current = -1,
	    	ac_total = 0,
	    	ac_active = true,
	    	ac_timestamp = 0,
	    	ac_cache = [],
	    	ac_cache_size = 0, 
	    	searchField ={},
	    	hovered_id = '',
	    	ac_server = '',
	    	SIZE_SMALL = '40x40',
	    	PRODUCT_NAME_SIZE = '85',
	    	EXTENSION = '.jpg',
	    	SERVER_FOLDER = 'thumbnails',
            MAX_PATH_LENGTH = 50,
	    	options = {
	    		hints : 'hints'
	    	};
	    
	    /**
	     * Fetches results for autocompletion from server
	     * @param {String} phrase
	     * @param {Number} timestamp
	     * 
	     * @author Piotr Deszynski
	     */
	    var fetchDelay = function(phrase, timestamp) {
	        /**
	         * Because the funciton is delayed fetch results only
	         * if current phrase in search field is the same as 
	         * currently typed in input
	         */
	        if ($.trim(searchField.val().toLowerCase()) === phrase.toLowerCase()) {
	            $.ajax({
	               dataType: 'jsonp',
	               url: ac_server + "/" + encodeURIComponent(phrase) + "?callback=?&t=" + timestamp,
	               success: function(data) {
	                   var t_from_response = parseInt(data['t']);
	                   if (t_from_response >= ac_timestamp) {
	                          ac_timestamp = t_from_response;
	                   }
	                   else return;
	                   
	                   ac_cache[phrase] = data['r'];
	                   ++ac_cache_size;
	                   displayResults(data['r'], phrase);
	               }
	            });
	        }   
	    },
	    /**
	     * Closes autocompleter suggestions
	     * @author Piotr Deszynski
	     */
	    close = function() {
	        ac_current = -1;
	        $('#' + options.hints).css('display', 'none');
	    },
	    
	    /**
	     * Handler used for managind arrows press and enter key
	     * 
	     * @param {Object} event
	     * 
	     * @author Piotr Deszynski
	     */
	    keydownHandler = function(event) {
	        
	        var itemSelector = '#ac_opt_',
	        	bigHint = '#bigHint_',
	        	ac_current_hover = hovered_id.replace('bigHint_','');
	        if (event.keyCode == undefined) return;
	        $('.ac_active').removeClass('ac_active');
	        switch(event.keyCode) {
	            case 40:
	            	//pressed down arrow
	                if (ac_current == -1) {
	                    ac_current = ac_current_hover === '' ? 0 : parseInt(ac_current_hover) + 1;
	                }
	                else {
	                    if (++ac_current >= ac_total) {
	                        ac_current = 0;
	                    }
	                }
	
	                $(bigHint + ac_current).addClass('ac_active');
	                complete($(itemSelector + ac_current));
	                
	                break;
	            case 38:
	            	//pressed up arrow
	                if (ac_current == -1) {
	                	ac_current = ac_current_hover === '' ? 0 : parseInt(ac_current_hover) - 1;
	                }
	                else {
	                    if(--ac_current < 0) {
	                        ac_current = ac_total - 1;
	                    }
	                }
	                $(bigHint + ac_current).addClass('ac_active');
	                complete($(itemSelector + ac_current));
	                break;
	            case 13:
	            	//pressed enter
	                if (ac_current != -1) {
	                    var el = $(itemSelector + ac_current);
	                    if (el.length) {
	                        complete(el, 1);
	                    }
	                }
	                else {
	                    close();
	                }
	                break;
	            case 37:
	            case 39:
	            case 8:
	            	//left or right arrow presed
	            	//or backspace pressed
	            	ac_current = -1;
	            	break;
	           }
	    },
	    /**
	     * Function called on suggestion completion
	     * (when arrow or enter was pressed)
	     * @param {jQuery} element Currenly selected suggestion
	     * @param {Number} submit If not undefined then also submit form for search
	     * 
	     * @author Piotr Deszynski
	     */
	    complete = function(element, submit) {
	        if (element.html() == null){
	            return;
	        }
	        
	        var value = element.html().replace(/<B>|<\/B>/gi,'');
	        
	        if (submit == undefined || submit == 2) {
	            searchField.val(value);
	        }
	        
	        if (submit != undefined) {
	            close();
	            
	            
	            var s_f = $('#ac_form');
	            
	            if (s_f.length) {
	                s_f = searchField.parent();
	            } 
	            
	            if (s_f.length)
	                s_f.submit();
	        }
	    },
	    
	    /**
	    
	     * Adjusting product name for product details link
	     * @param {String} name Product name 
	     * @author Alexandru Burlacu
	     */
        adjustingHref = function(name) {
            if (name.length > 0) {
                name = $.trim(name);
                name = name.replace('&', 'and');
                name = name.replace(/[^a-zA-Z0-9,\s]/g, '-');
                name = name.replace(/\s+/g, '-');
                }
            return name;
        },
        /**
	     * Adding of category path to each product suggestion
	     * query completion
	     *
	     * @author Alexandru Burlacu
	     */
        addCategoryPath = function(id, categoryPath) {
            var path = eval('(' + categoryPath + ')'),
                categoryName = "",
                categoryLink = "",
                upperCategoryName = "",
                categoryLinkName = "";
            $.each(path, function(key, value) {
                //set category names in link
                categoryLinkName = adjustingHref(value.name + upperCategoryName);
                //check if full category names in link are not too big
                categoryLinkName = categoryLinkName.length > MAX_PATH_LENGTH ? adjustingHref(value.name) : categoryLinkName;
                categoryName = value.category_id > 1 ? value.name : "",
                categoryLink = categoryName !== "" ? Uwish.Options.baseUrl + "/" + categoryLinkName +  "-" + value.category_id  : "",
                //store upper category except with root category
                upperCategoryName = key > 0 ? "-" + value.name : upperCategoryName;
				if (key > 1 ) {
					$('#' + id)
						.append(
							$('<span></span>')
							.attr('class', 'itemDescriptionCategory')
							.text(">>")
						);
				}
				$('#' + id)
				.append(
						$('<a></a>')
						.attr('class', 'itemDescriptionCategory')
						.attr('href', categoryLink)
						.text(categoryName)
				);
	    	});
	    },
	    /**
	     * Displays results for specified phrase.
	     * 
	     * @param {Array} results
	     * @param {String} phrase
	     * @author Alexandru Burlacu
	     */
	    displayResults = function(results, phrase) {
	    	//empties results container and sets its width so it matches search
	    	var names = [],
	        	parameters = [],
	        	thumb ='';
	    	if(results != null) {
		    	$.each(results, function(key, value) { 
		    		 names.push(key); 
		    		 parameters.push(value);
		    	});
	    	}
	    	var el = $('#autocompleter').empty().width(searchField.width());
	        	ac_total   = names.length;
	        	ac_current = -1;
	        if (ac_total > 0 ) {
	             phrase = $.trim(searchField.val());
	             phrase = phrase.toLowerCase();
	             if (phrase.length > 0) {
	                 var pos = searchField.position();
	                 el.css({top: pos.top + 24, left: pos.left});
	                 el.append(
	                	$('<div></div>')
	 	                	.addClass('searchBigHint')
	 	                 	.attr('id', 'hints')
	                    );
					$('#' + options.hints).append(
						$('<div></div>')
							.addClass('closeSuggestions')
							.attr('align', 'right')
							.append(
								$('<a></a>')
									.attr('href', '#')
									.html('<b>Close</b>')
									.bind('click', function(event){
										close();
									})
						)
					);
					for (var i = 0; i < ac_total; ++i) {
						if (parameters[i].downloaded !== 1) {
							thumb = parameters[i].thumb;
						}
						else {
							thumb = parameters[i].md5_thumb; 
							thumb = "/" + thumb.substr(0, 2) + "/" + thumb.substr(2, 2) + "/" + thumb.substr(4,2) + "/" + thumb;
							thumb = Uwish.Options.staticUrl + "/" + SERVER_FOLDER + thumb + "_" + SIZE_SMALL + EXTENSION;
						}
						var shardId = 1000 + parseInt(parameters[i].shard_id),
							productLinkName = Uwish.productNameInLInk(adjustingHref(names[i])),
							productDetails = Uwish.Options.baseUrl + "/" + productLinkName + "-" + shardId + parameters[i].product_id + ".html",
							query = '<b>' + phrase + '</b>';
						names[i] = Uwish.truncate(names[i], PRODUCT_NAME_SIZE);
						$('#' + options.hints)
							.append(
								$('<div></div>')
									.addClass('searchBigHintItem')
									.attr('id', 'bigHint_' + i)
									.append(
										$('<div></div>')
											.addClass('searchBigHintItemPhoto')
											.append(
												$('<img></img>')
													.addClass('resize_images_20')
													.attr('src',  thumb)
											)
									)
									.append(
										$('<div></div>')
											.addClass('searchBigHintItemDescription')
											.append(
												$('<a></a>')
													.attr('href', productDetails)
													.attr('id', 'ac_opt_' + i)
													.attr('class', 'itemDescriptionName')
													.text(names[i])
											)
											.append(
													$('<div></div>')
														.attr('id', 'categoryPath_' + i)
											)
											.bind('click', function(event){
												window.location=$(this).find("a").attr("href");
											})
									)
									.bind('mouseenter', function(event){
										ac_current = -1;
										$('.ac_active').removeClass('ac_active');
										$(this).addClass('ac_active');
										hovered_id = $(this).attr('id');
									})
									.bind('mouseleave', function(event){
										hovered_id = '';
									})
							);
						//mark query in the product name
						$('#' + 'ac_opt_' + i).html($('#' + 'ac_opt_' + i).html().replace(phrase, query));
						addCategoryPath('categoryPath_' + i, parameters[i].category_path);
					}
					$('#' + options.hints).css('display', 'block');
	             }
	             else {
	                 close();
	             }
	       }
	    };
	    
	    /**
	     * Public interface of Autocompleter class
	     */
	    return {
	        /**
	         * Function binds needed events
	         * 
	         * @author Piotr Deszynski
	         * 
	         */
	        bind: function(queryField, host) {
	        	//set search query Field
	        	searchField = $('#' + queryField);
	        	
	        	//set host
	        	ac_server = host;
	            
	            if (typeof ac_server === 'undefined') {
	                //when server wasn't specified then autocompleter cannot be enabled
	                return close();
	            }
	            //sets autocopmlete attribute to off, so browser won't display its own suggestions
	            searchField.attr('autocomplete', 'off');
	            
	            //every keyup makes suggestion
	            searchField.bind('keyup', function(event){
	                /**
	                 * Holds current timestamp so it thanks to it when response comes back
	                 * from server it is known if current response is newer than last one.
	                 */
	                var now = new Date().getTime(), 
	                /**
	                 * if one of following keys were pressed then do nothing
	                 * 38, 40 - up/down arrows, 13 - enter, 27 - esc
	                 */
	                returnKeyCodes = [40, 38, 13, 27],
	                phrase = $.trim($(this).val());
	                phrase = phrase.toLowerCase();
	                
	                if (returnKeyCodes.indexOf(event.keyCode) != -1 || !ac_active) return;
	                
	                if ( phrase.length  > 0 ) {
	                    //check if phrase results weren't already in cache
	                    if (ac_cache[phrase] !== undefined) {
	                        //in that situation just display results
	                        displayResults( ac_cache[phrase], phrase);
	                        return;
	                    }
	                    else {
	                        setTimeout ( function(){fetchDelay(phrase, now);}, 0 );
	                    }
	                }
	                else {
	                   close();
	                }
	            });
	            $(document).bind('keyup', function(event){
	                //close suggestions whenever escape key was pressed
	                if (event.keyCode === 27) {
	                    close();
	                    return;
	                }
	                keydownHandler(event);
	            });
	            
	            $('body').bind('click.autocompleter', function() {
	                /*
	                 * If anything than input or suggestion itself was clicked
	                 * then close suggestions. Most important: all elements which
	                 * shouldn't close suggestion has to contain 'ac_' text in its
	                 * id.
	                 * 
	                 * Piotr Deszynski
	                 */
	                if ($(this).attr('id').indexOf('ac_') === -1) {
	                    close();
	                }
	            });
	            return this;
	        },
	        /**
	         * Reference to private disable function, so it
	         * can be called internally and externally
	         * 
	         * @author Piotr Deszynski
	         */
	        disable: close
	    };
	})();

	/** 
	 * 
	 * Additional Help switching
	 * @param {String} selector Selected item 
	 * @author Alexandru Burlacu
	 * @constructor
	 */
	Uwish.AdditionalHelp = function(selector) {
		$(selector).click(function () {
			var fileName = $(this).attr('name');
			$.ajax({
				url: Uwish.Options.baseUrl + "/additional-help.html",
				data: {'fileName' : fileName, format : 'json'},
				type: 'post',
				dataType: 'json',
				async: true,
				success : function (response) {
					$('#info').html(response.additionalBox);
				},
				error : function (request , error, message ) {
				}
			});
		});
	};
	
	/**
	 * 
	 * Big search field effects
	 * @param {String} queryField User Query field
	 * @author Alexandru Burlacu
	 */
	Uwish.bigSearchEffects = function (queryField, formId) {
		var focused = true,
			text = Uwish._("Find Products"),
			focusedClass = 'searchBigInFocused',
			defaultClass = 'searchBigIn';
		$(queryField).val(text);
		$(queryField).focus(function () {
			if (focused) {
				$(this).addClass(focusedClass);
				$(this).removeClass(defaultClass);
				$(this).val("");
				focused = false;
			}
		});
		$(formId).submit(function () {
		    if ($(queryField).val() === text) {
		        $(queryField).val("");
		    }
		});
		
		
		$(queryField).blur(function () {
			//check if query has not been entered into the query field 
			var isEmpty = $.trim($(queryField).val()) === '' || $(queryField).val() === text ? true : false; 
			if (!focused && isEmpty ) {
				$(this).removeClass(focusedClass);
				$(this).addClass(defaultClass);
				$(queryField).val(text);
				focused = true;
			}
		});
	};

	/**
	 * User Alerts
	 * 
	 * @param {String} selector Selected tab
	 * @param {String} activeClass Active class name
	 * @return 
	 * @author Alexandru Burlacu
	 */
	Uwish.UserAlerts = (function() {
		var status = 0,
			query = "",
			ALERT_DOES_NOT_EXIT = 0,
			limitToDisplay = 20,
			alertId = 0,
			id = 0,
			actionType = 0,
			opt = {
					'firstButton' : 'first',
					'secondButton' : 'second',
					'query' : 'query',
					'dialog' : 'dialog',
					'addAlertClass' : 'addAlert',
					'warning' : 'alertWarning'
				},
			itemCount = 0,
			DEFAULT_ACTION = 0,
			addPending = false,
			EDIT_ACTION = 1;
			
		return function(limit, count) {
			var self = this;
			itemCount = count;
			this.messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
			limitToDisplay = limit > 0 ? limit : limitToDisplay ;
			/**
			 * 
			 * Delete alert item
			 * 
			 * @author Alexandru Burlacu
			 */
			var deleteItem = function (alertId) {
				$.ajax({
					url: 'delete-alert.html',
					data: {'alertId' : alertId, format : 'json'},
					type: 'post',
					dataType: 'json',
					async: true,
					success : function (response) {
							$(this).remove();
							if (response.code >= 0) {
								itemCount--;
								$('#' + opt.dialog).dialog('close');
								$('#alert_' + alertId).remove();
								if (itemCount === 0) {
									$('#alerts_content').remove();
									$('.noResults').show();
								}
							}else  {
								$('#' + opt.dialog).dialog('option', 'title', 'Warning');
							}
					}
				});
			},
			/**
			 * 
			 * Edit alert item
			 * 
			 * @author Alexandru Burlacu
			 */
			editItem = function (alertId) {
				query =  $('#inputQuery_' + alertId).val();
				$('.' + opt.warning +'').remove();
				if (query.length <= limitToDisplay) {
					$.ajax({
						url: 'edit-alert.html',
						data: {'alertId' : alertId, 'query' : query, format : 'json'},
						type: 'post',
						dataType: 'json',
						async: true,
						success : function (response) {
								$(this).remove();
								if (response.code >= 0) {
									$('#' + opt.secondButton + alertId).html('<span>'+ Uwish._('delete') +'<span>');
									$('#' + opt.firstButton + alertId).html('<span>'+ Uwish._('edit') +'<span>');
									$('#' + opt.query + alertId).text(query);
									$('.manageAlerts').show();
									actionType = DEFAULT_ACTION;
								}else  {
									$('#' + opt.dialog).dialog('option', 'title', 'Warning');
								}
						}
					});
				} else {
					$('#' + opt.query + alertId).append('<span class="'+ opt.warning +'">'+ Uwish._('Query is too long') +'<span>');
				}
			},
			/**
			 * 
			 * OpenDialog
			 * 
			 * @author Alexandru Burlacu
			 */
			openDialog = function (id) {
				var title = Uwish._("Deleting");
				$('#' + opt.dialog).dialog({
					title: title,
					height: 150,
					width: 400,
					modal: true,
					resizable: false,
					buttons : [
					    {
					    	text : Uwish._("Yes"),
							click : function() {
								deleteItem(id);
								$(this).dialog("close");
							}
						},
						{
							text : Uwish._("No"),
							click : function() {
								$(this).dialog("close");
							}
						}
					]
				});
			};
			/**
			 * 
			 * Alert adding
			 * 
			 * @author Alexandru Burlacu
			 */
			this.addAlert = function(selector, query) {
				$('.' + opt.addAlertClass).hide();
				if (status == ALERT_DOES_NOT_EXIT) {
					$.post(Uwish.Options.baseUrl + "/check-query-alert.html", {'query' : query, format : 'json'},
					function (response) {
						if (response.code == ALERT_DOES_NOT_EXIT){ 
							$('.' + opt.addAlertClass).fadeIn();
							var truncatedQuery = Uwish.truncate(query, limitToDisplay);
                            $('#spnQuery').text(truncatedQuery).attr('title', query);
							$('.' + opt.addAlertClass).show();
						} else { 
							$('.' + opt.addAlertClass).hide();
						}
					});
				}
				$(selector).click(function() {
				if (!addPending) {
				    addPending = true;
					$.ajax({
					    url: Uwish.Options.baseUrl + "/add-query-alert.html",
					    data: {'query' : query, format : 'json'},
					    type: 'post',
					    dataType: 'json',
					    async: true,
					    success : function (response) {
							if (response.code > 0){
								$('.' + opt.addAlertClass).hide();
								self.messages.showMessage(Uwish._('Alert has been created successfully. You can view your alerts in your settings page.'), {delay: self.DELAY});
							} 
							addPending = false;
					    },
					    error: function (request, status, error) {
					    	self.messages.showMessage(Uwish._('An error occured while creating your alert. Please try again later.'), {delay: self.DELAY});
					    	addPending = false;
				        }
					});
				}
				});
			};
			/**
			 * 
			 * FirstAction - Edit/Accept Editing alert
			 * 
			 * @author Alexandru Burlacu
			 */
			this.firstAction  = function (selector) {
				//the changes can be accepted if editing is initiated
				$(selector).click(function() {
					id = $(this).attr('id');
					alertId = id.replace(opt.firstButton, '');
					if(actionType === EDIT_ACTION) { //accept changes
						editItem(alertId);
					} else { //initiate alert editing
						actionType = EDIT_ACTION;
						$('#' + opt.firstButton + alertId).html('<span>'+ Uwish._('accept') +'<span>');
						$('#' + opt.secondButton + alertId).html('<span>'+ Uwish._('cancel') +'<span>');
						query = $('#' + opt.query + alertId).text();
						$('#' + opt.query + alertId).html(
			                $('<input></input>')
			                	.attr('id', 'inputQuery_' + alertId)
			                	.attr('type', 'text')
			                	.addClass('alerts')
			                    .val(query)
			                 );
				       $('.manageAlerts').hide();
				       $('#' + opt.firstButton + alertId).show();
				       $('#' + opt.secondButton + alertId).show();
					};
				});
			},
			/**
			 * 
			 * SecondAction - cancel/delete alert
			 * 
			 * @author Alexandru Burlacu
			 */
			this.secondAction = function (selector) {
				//the alert can be canceled only if editing is initiated
				$(selector).click(function() {
					id = $(this).attr('id');
					alertId = id.replace(opt.secondButton, '');
					if(actionType == EDIT_ACTION) { //cancel changes
						$('#' + opt.secondButton + alertId).html('<span>'+ Uwish._('Delete') +'<span>');
						$('#' + opt.firstButton + alertId).html('<span>'+ Uwish._('Edit') +'<span>');
						$('#' + opt.query + alertId).text(query);
						actionType = DEFAULT_ACTION;
						$('.manageAlerts').show();
					} else { //initiate alert deleting
						$('.messages').hide();
						$('#deleteAlert').show();
						openDialog(alertId);
					}
					
				});
			};
		};
	})();
	
    Uwish.ResetForm = (function(options) {
        return function() {
            $('input[name="shops"]').click(
                function(event) {
                    $('input[name="shop[]"]').removeAttr('checked');
                    event.preventDefault();
                }
            );
            $('input[name="brands"]').click(
                function(event) {
                    $('input[name="brand[]"]').removeAttr('checked');
                    event.preventDefault();
                }
            );
        };
    })();

    /**
     * 
     * Browse Categories show/hide functionality
     * 
     * @author Golban Sergiu
     */
   Uwish.BrowseCategories = (function() {
	   	var images = {
	   		'smallInactive': 'browseSmall.png',
	   		'smallActive': 'browseActiveSmall.png',
	   		'bigInactive': 'browseInactive.png',
	   		'bigActive': 'browseActive.png'
	   		},
   		checkSize = function() {
	   		return $('a.active').parent().parent().hasClass('searchSmallForm') ? 'small' : 'big';
   		};

        return function (){
            $('.closeBrowse').click(
                function() {
                	var size = checkSize();
                    $('.browseCategoriesContainer').fadeOut();
                    $('a.active').css("background-image", "url(" + Uwish.Options.staticUrl + "/images/" + images[size + 'Inactive'] + ")");
                });
            $('.advancedSearchButton.start a.active, .advancedSearchButton a.active').click(
                function(event) {
                	var size = checkSize();
                    if($('.browseCategoriesContainer').is(':visible')) {
                        $(this).css("background-image", "url(" + Uwish.Options.staticUrl + "/images/" + images[size + 'Inactive'] + ")");
                        $('.browseCategoriesContainer').fadeOut();
                    } else {
                        $('.browseCategoriesContainer').fadeIn();
                        $(this).css("background-image", "url(" + Uwish.Options.staticUrl + "/images/" + images[size + 'Active'] + ")");
                    }
                    event.preventDefault();
                }
            );
        };
    })();

    Uwish.DisplayMessage = (function(options) {
        return function() {
            var messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
            $('a[name="emptyFavourites"]').click( function () {
                    messages.showMessage(Uwish._('Please choose you favourite shops and brands first ') + '<a href="' + Uwish.Options.baseUrl + '/favourites.html">' + Uwish._('here') + '</a>', {delay: self.DELAY});
            });
        };
    })();

      /**
     * 
     * Send Activation Emails
     * 
     * @author Golban Sergiu
     */
   Uwish.SendActivationEmail = (function() {
       var SUCCESS = 0,
       FAILED_SEND_CONFIRMATION_EMAIL = 5,
           pending = false;
        return function (selector){
            $(selector).click(function() {
                if (pending) { return; }
                pending = true;
                $('#emailActivationBox').fadeOut();
                $.ajax({
                    url: Uwish.Options.baseUrl + "/send-activation-email.html?format=json",
                    type: 'post',
                    dataType: 'json',
                    success: function(response) {
                        var messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
                        if (response.code == SUCCESS) { 
                            messages.showMessage(Uwish._('Soon you will receive an email with activation link'), {delay: self.DELAY});
                            $('#emailActivationBox').html('<p>Activation email was sent, please check your inbox</p>');
                        }
                        else if (response.code == FAILED_SEND_CONFIRMATION_EMAIL) {
                            //already exist
                            pending = false;
                            messages.showMessage(Uwish._('Failed to send activation email, please try again'), {delay: self.DELAY});
                        }
                        $('#emailActivationBox').fadeIn();
                    },
                    error: function(request) {
                        pending = false;
                        messages.showMessage(Uwish._('Failed to send activation email, please try again'), {delay: self.DELAY});
                        $('#emailActivationBox').fadeIn();
                    }
                });
            });
        };
    })();

    /**
     * Truncate string helper
     *
     * @param string name Any string e.g product
     * @param {Integer} size Limit size for cutting
     * @author Alexandru Burlacu
     */
    Uwish.truncate = (function(name, size) {
        //cut string
        return name.length > size ? name.substr(0, size) + "..." : name;
   });
    /**
     * Truncate path helper
     *
     * @param array name Any Path (e.g category path)
     * @param {Integer} size Limit size for cutting
     * @author Alexandru Burlacu
     */
    Uwish.truncateBreadcrumbs = (function(path, size) {
        var result = '';
        if(path.length > 0) {
			var delimiter = ' >> ',
				//create category path using delimiter
				path = path.join(delimiter);
				// truncate category path
			result = path.length > size ? $.trim(path.substr(0, size), '>') + '...' : path;
		}
	   return result;
    });
    /**
     * Adjust ProductName in link
     *
     * @param string name Product Name
     * @author Alexandru Burlacu
     */
    Uwish.productNameInLInk = (function(name) {
        var WORD_LIMIT = 5,
            separator = '-',
            words = name.split('-', WORD_LIMIT + 1);
        //remove last-word because its contains the rest of words
        words.splice(WORD_LIMIT, 1);
        //implode word into string again
        name = words.join(separator);
        return name;
    });
	/* Account class
	 *
	 * @author Alexandru Burlacu
	 */
	Uwish.Account = (function() {
		var opt = {'dialog' : 'dialog'};
		return function() {
			var self = this;
			this.messages = new Uwish.Messages({type: Uwish.Messages.TYPE.correct});
			/**
			 *
			 * Delete item
			 *
			 * @author Alexandru Burlacu
			 */
			var deleteItem = function () {
				$.ajax({
					url: 'deactivate-account.html',
					data: {format : 'json'},
					type: 'post',
					dataType: 'json',
					async: true,
					success : function (response) {
							$(this).remove();
							if (response.results == 1) {
								$('#' + opt.dialog).dialog('close');
								window.location = Uwish.Options.baseUrl;
								self.messages.showMessage(Uwish._('Your account has been successfully deactivated'), {delay: self.DELAY});
							}else  {
								$('#' + opt.dialog).dialog('option', 'title', 'Warning');
							}
					}
				});
			};
			/**
			 *
			 * OpenDialog
			 * @param {String} selector Selected class
			 * @author Alexandru Burlacu
			 */
			this.deactivateAccount = function (selector) {
				$(selector).click(function () {
					var title = Uwish._("Account permanent deactivation");
					$('#' + opt.dialog).dialog({
						title: title,
						height: 200,
						width: 400,
						modal: true,
						resizable: false,
						buttons : [
                            {
                                text : Uwish._("Yes"),
								click : function() {
									deleteItem();
									$(this).dialog("close");
								}
							},
							{
								text : Uwish._("No"),
								click : function() {
									$(this).dialog("close");
								}
							}
						]
					});
				});
			};
		};
	})();
})();

