/*
 * The starting part of all "ViartShop Russian Edition" JavaScript possibilities.
 * Developed by Makarychev Yurii (http://makarychev.ru/) aka iSlayter (http://islayter.com/)
 */
$().ready(function() {
	/*
	 * Instantiate autocomplete
	 */
	initAutoComplete();
    
    /*
     * Instantiate slide menu
     */
    initSlideMenu('CategoriesSlideMenu', 'slow', true);
    
    /*
     * Instantiate scrollers
     */
    initScrollers('imgForScroll', 'imgScrollPrev', 'imgScrollNext');
});

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 
/*                The next functions used for make all of this stuff to work                       */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

function initScrollers(idOfImagesList, idNavlinkPrev, idNavlinkNext) {
	$('#' + idOfImagesList).serialScroll({
		items:'li',
		prev:'#' + idNavlinkPrev,
		next:'#' + idNavlinkNext,
		offset:false, //when scrolling to photo, stop 230 before reaching it (from the left)
		start:0, //as we are centering it, start at the 2nd
		duration:1200,
		force:true,
		stop:true,
		lock:false,
		cycle:true, //don't pull back once you reach the end
		easing:'easeOutQuart', //use this easing equation for a funny effect
		jump: true //click on the images to scroll to them
	});
}

/*
 * Auto complete function.
 */
function initAutoComplete() {
	$("#productSearchTerm").blur(function() { sform(0, 'productSearchTerm', 'Try to use search in our products (with autosuggest) ...'); });
	$("#productSearchTerm").focus(function() { sform(1, 'productSearchTerm', 'Try to use search in our products (with autosuggest) ...'); });
    $("#productSearchTerm").autocomplete('products_search_autocomplete.php', {
        minChars: 2,
        width: 411,
        selectFirst: false,
        extraParams: {
            categoryId: function() {
                return $("#productSearchCategory").val();
            }
        },
        formatItem: function(formatItem) {
            return formatItem[1];
        },
        formatResult: function(formatResult) {
            return formatResult[1];
        }
    }).result(function(event, resultItem) {
        $('#productSearchSubmitBtn').attr('disabled', 'disabled')
        location.href = 'product_details.php?item_id=' + resultItem[0];
    });
    	    
    $("#productSearchCategory").click(function(){ $('.ac_results').css('display','none'); $("#productSearchTerm").val(''); });
    $("#productSearchCategory").change(function(){ $('.ac_results').css('display','none'); });
}

/*
 * Slide menu function.
 * Developed by Makarychev Yurii (http://makarychev.ru/) aka iSlayter (http://islayter.com/)
 */
function initSlideMenu(id, speed, accordion) {
   mustBeOpenedTabs = ($.cookie('opened' + id)) ? $.cookie('opened' + id).split('=') : new Array();
   /*mustBeOpenedTabs.sort();
   if (mustBeOpenedTabs.length > 0) {
	   for (i=0; i < mustBeOpenedTabs.length; i=i+1) {
		   setTimeout('$("#' + id + mustBeOpenedTabs[i] + '").next().slideDown("' + speed + '")', 500 * i);
	   }
   }*/
   $('ul#' + id + ' > li:has(ul) a').click(
      function() {         
         alreadyOpenedTabs = ($.cookie('opened' + id)) ? $.cookie('opened' + id).split('=') : new Array();
         totalOpenedTabs   = (alreadyOpenedTabs.length > 0) ? alreadyOpenedTabs.length : 1;
         
         curElem = $('#' + $(this).attr('id'));
      	 realId = $(this).attr('id').substr(strlen(id));
     	  	 
         if (curElem.next().css('display') == 'none') {
        	 
        	 /*
        	  * Opening
        	  */
        	if (true == accordion) {
               $('ul#' + id + ' li ul:visible').slideUp(speed);
               accordionOpenedItem = realId;
        	} else {
               alreadyOpenedTabs[alreadyOpenedTabs.length] = realId;
        	}
         	$(this).next().slideDown(speed);
         	
         } else {
        	 
        	 /*
        	  * Closing
        	  */
        	if (true == accordion) {
        	   $(this).next().slideUp(speed);
        	   accordionOpenedItem = '';
        	} else {
               $(this).next().slideUp(speed);         
               for (i=0; i < totalOpenedTabs; i = i+1)
               {
                  if (alreadyOpenedTabs[i] == realId) {
                     delete alreadyOpenedTabs[i];
                  }
               }
            }
         }        	
         /*
          *  writing to cookies separated by "=" integer part of elements ids for the next time we can easy open them
          *  and filter elements with UNDEFINED type (because after delete there is UNDEFINED element exist in array [no value]
          *  and we don't want to write in cookie "==3" (if 1 and 2 was deleted) because in next time in array will be
          *  exist 2 empty elements
          */
         toCookie = '';
         if (true == accordion) {
             toCookie = accordionOpenedItem;
      	 } else {
            for (i=0; i < alreadyOpenedTabs.length; i=i+1)
            {
               if (typeof(alreadyOpenedTabs[i]) != 'undefined') {
                  toCookie = (toCookie != '') ? toCookie + '=' + alreadyOpenedTabs[i] : alreadyOpenedTabs[i]; 
               }
            }
      	 }
         $.cookie('opened' + id, toCookie, { path: '/', expires: 365 });
         return false;
      }
   );
   $('ul#' + id + ' li ul a').unbind();
}


/*
 * Function for changing text at input fields.
 * Developed by Makarychev Yurii (http://makarychev.ru/) aka iSlayter (http://islayter.com/)
 */
function sform(show, id, keyword) {
	el = $('#' + id);
	if (show == 1 && el.val() == keyword) {       
		el.val('');
	} else if (el.val() == '') {
		el.val(keyword);
	}
}


/*
 * Usefull function for providing access to a cookies via jQuery
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/*
 * Same that php-function strpos()
 */
function strpos (haystack, needle, offset) {
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}


/*
 * Same that php-function strlen()
 */
function strlen (string) {
    var str = string+'';
    var i = 0, chr = '', lgth = 0;

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) {
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) {
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) {
                throw 'Low surrogate without preceding high surrogate';
            }
            return false;
        }
        return str.charAt(i);
    };

    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        }
        lgth++;
    }
    return lgth;
}

/*
 * Function for effects in sliders.
 */
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};
