/*
*	Track — id of parent elenemt
*	Tracker — id of tracked element
*	OnUpdate — function whitch calls on each value change
*	OnComplete — function whitch calls on end of the drag
*	FingerOffset — distance between mouse pointer and corner tracker's edge
*	FormatNumbers — lead numders in hairlines with spaces
*	Min & Max — range of vaues
*	MinSpace — minimum difference between Min & Max
*	RoundTo — values will be rounded to this value
*	Margins — indent between Track & Tracker
*	AllowedValues — force Tracker to stick to the values
*
*	OnUpdate — function whitch called each time, when Tracker moved
*	OnComplete — function whitch called when user stop draging
*/
function classFilter(r,m,not){
	m = " " + m + " ";
	var tmp = [];
	for ( var i = 0; r[i]; i++ ) {
		var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
		if ( not ^ pass )
			tmp.push( r[i] );
	}
	return tmp;
}


function cDoubleTrackBar(Track, Tracker, Settings) {
	switch(typeof Track){
		case 'string': this.Track = document.getElementById(Track); break;
		case 'object': this.Track = Track; break;
	}
	switch(typeof Tracker){
		case 'string': this.Tracker = document.getElementById(Tracker); break;
		case 'object': this.Tracker = Tracker; break;
	}
	if (!Track || !Tracker)
		return false;
	this.OnUpdate = Settings.OnUpdate;
	this.OnComplete = Settings.OnComplete;
	this.FingerOffset = Settings.FingerOffset || 0;
	this.FormatNumbers = Settings.FormatNumbers || false;
	this.Min = Settings.Min || 0;
	this.Max = Settings.Max || 100;
	this.MinSpace = Settings.MinSpace || 0;
	this.RoundTo = Settings.RoundTo || 1;
	this.Margins = Settings.Margins || 0;
	this.AllowedValues = Settings.AllowedValues || false;
	this.Disabled = (typeof Settings.Disabled != 'undefined') ? Settings.Disabled : false;

	if (this.Min >= this.Max)
		this.Max = this.Min +1;
	this.MinPos = this.Min;
	this.MaxPos = this.Max;
	if (this.Max - this.Min < this.MinSpace)
		this.MinSpace =  this.Max - this.Min;
	if (this.Max - this.Min < this.RoundTo)
		this.RoundTo =  this.Max - this.Min;
	this.MinSpace = Math.ceil(this.MinSpace/this.RoundTo)*this.RoundTo;


	this.Track.style.width = (this.Track.clientWidth || this.Track.offsetWidth) + 'px';
	this.OnTrackMouseDown = this.bindAsEventListener(this.TrackMouseDown);
	this.OnDocumentMouseMove = this.bindAsEventListener(this.DocumentMouseMove);
	this.OnDocumentMouseUp = this.bindAsEventListener(this.DocumentMouseUp);

	this.bindEvent(this.Track, 'mousedown', this.OnTrackMouseDown);

	this.TrackerLeft = 0;
	this.UpdateTracker(this.Track.offsetWidth + this.FingerOffset);
	if (typeof this.OnUpdate == 'function') {
		this.OnUpdate.call(this);
	}
}
cDoubleTrackBar.prototype = {

	TrackMouseDown: function(event) {
		this.TrackerLeft = this.Tracker.offsetLeft - this.Margins;
		this.TrackerRight = this.TrackerLeft + this.Tracker.offsetWidth;

		this.TrackerOffsets = this.getOffsets(this.Track);

		var X = event.clientX + document.documentElement.scrollLeft;
		X -= this.TrackerOffsets[0];

		this.Left = Math.abs(this.TrackerLeft-X+this.Margins) <= Math.abs(this.TrackerRight-X+this.Margins);

		if (typeof this.Disabled == 'function') {
			if ( this.Disabled.call(this) )
				return true;
		} else if ( this.Disabled )
			return true;
		
		this.UpdateTracker(X);

		this.bindEvent(document, 'mousemove', this.OnDocumentMouseMove);
		this.bindEvent(document, 'mouseup', this.OnDocumentMouseUp);

		return this.stopEvent(event);
	},
	DocumentMouseMove: function(event) {
		this.UpdateTracker(event.clientX + document.documentElement.scrollLeft - this.TrackerOffsets[0]);
		return this.stopEvent(event);
	},
	DocumentMouseUp: function(event) {
		this.unbindEvent(document, 'mousemove', this.OnDocumentMouseMove);
		this.unbindEvent(document, 'mouseup', this.OnDocumentMouseUp);

		if (typeof this.OnComplete == 'function') {
			this.OnComplete.call(this);
		}
		return this.stopEvent(event);
	},
	UpdateTracker: function(X){
		var _LogicWidth = this.Track.offsetWidth - this.Margins*2 - 1;
		var _minSpace = Math.floor(_LogicWidth*this.MinSpace/(this.Max-this.Min));
		var _oldMin = this.MinPos;
		var _oldMax = this.MaxPos;

		X -= this.Margins;
		if (this.Left) {
			X += this.FingerOffset;
			this.TrackerLeft = Math.max(0, Math.min(this.TrackerRight - _minSpace - 1, X));
			this.MinPos = Math.round((this.Min + this.TrackerLeft*(this.Max-this.Min)/_LogicWidth) / this.RoundTo) * this.RoundTo;
			if (this.MinSpace >= this.MaxPos - this.MinPos) {
				this.MinPos = this.MaxPos - this.MinSpace;
			}
			if (this.AllowedValues) {
				this.TrackerLeft = Math.round(_LogicWidth*(this.MinPos - this.Min)/(this.Max - this.Min));
			}
		} else {
			X -= this.FingerOffset;
			this.TrackerRight = Math.max(this.TrackerLeft + _minSpace + 1 , Math.min(_LogicWidth + 1, X));
			this.MaxPos = Math.round((this.Min + (this.TrackerRight-1)*(this.Max-this.Min)/_LogicWidth) / this.RoundTo) * this.RoundTo;
			if (this.MinSpace >= this.MaxPos - this.MinPos) {
				this.MaxPos = this.MinPos + this.MinSpace;
			}
			if (this.AllowedValues) {
				this.TrackerRight = Math.round(_LogicWidth*(this.MaxPos - this.Min)/(this.Max - this.Min))+1;
			}
		}
		this.Tracker.style.width = (this.TrackerRight - this.TrackerLeft) + 'px';
		this.Tracker.style.left = (this.Margins + this.TrackerLeft) + 'px';

		if (typeof this.OnUpdate == 'function')
			if ( !this.AllowedValues || (this.AllowedValues && (_oldMax!=this.MaxPos || _oldMin!=this.MinPos)) )
				this.OnUpdate.call(this);
	},
	
	AddHairline: function (pos) {
		var _Touch = this.Track.appendChild( document.createElement('div') );
		var _LogicWidth = this.Track.offsetWidth - this.Margins*2 - 1;
		
		_Touch.style.left = this.Margins + _LogicWidth/(this.Max-this.Min)*(pos-this.Min) + 'px';
		_Touch.className = 'touch';
		_Touch.innerHTML = "<span>" + (this.FormatNumbers ? this.leadSpaces(pos) : pos) + "</span>";
	},
	
	AutoHairline: function(num) {
		if (num >= 1)
			this.AddHairline(this.Min);
		if (num >= 2)
			this.AddHairline(this.Max);
		if (num >= 3) {
			num--;
			var diff = this.Max - this.Min;
			var roundTo = [10, 20, 50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000, 250000, 500000, 1000000];
			var DoRound = 1;
			for (var i=0; roundTo[i]; i++) {
				DoRound = roundTo[i]/10;
				if (roundTo[i]>diff)
					break;
			}
			for (var i=1; i<num; i++) {
				var val = this.Min + diff/num*i;
				val = Math.round(val/DoRound)*DoRound;
				this.AddHairline(val);
			}
		}
	},
	
	
	getOffsets: function(element) {
	    var valueT = 0, valueL = 0;
	    do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
	    } while (element);
	    return [valueL, valueT];
	},
	leadSpaces: function(numb) {
		var res = '';
		numb = numb.toString();
		var l = numb.length;
		for (var i=l; i>0; i--)
			if ((l-i)%3==2)
				res = '&nbsp;'+numb.charAt(i-1)+res;
			else
				res = numb.charAt(i-1)+res;
		return res;
	},
	bindEvent: function(element, event, callBack){
		if (element.addEventListener) {
			element.addEventListener(event, callBack, false);
		} else {
			element.attachEvent('on' + event, callBack);
		}
	},
	unbindEvent: function(element, event, callBack){
		if (element.removeEventListener) {
			element.removeEventListener(event, callBack, false);
	    } else if (element.detachEvent) {
			element.detachEvent('on' + event, callBack);
	    }
	},
	bindAsEventListener: function (callBack) {
		var _object = this;
		return function(event) {
			return callBack.call(_object, event || window.event);
		}
	},
	stopEvent: function (event){
		if (event.preventDefault) {
			event.preventDefault();
			event.stopPropagation();
		} else {
			event.returnValue = false;
			event.cancelBubble = true;
		}
		return false;
	}
}

$.fn.equalHeight = function ()
{
	var tallest = 0;
	this.each(function(){
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	$(this).height(tallest);
	return true;
}
// JQuery URL Parser
// Written by Mark Perkins, mark@allmarkedup.com
// License: http://unlicense.org/ (i.e. do what you want with it!)

$.url = function()
{
	var segments = {};
	
	var parsed = {};
	
	/**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
  	var options = {
	
		url : window.location, // default URI is the page in which the script is running
		
		strictMode: false, // 'loose' parsing by default
	
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}
		
	};
	
    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */		
	var parseUri = function()
	{
		str = decodeURI( options.url );
		
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}

		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
  	 * 
	 * @param string key The key whose value is required
     */		
	var key = function( key )
	{
		if ( $.isEmptyObject(parsed) )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		} 
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}
	
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	
	/**
     * Returns the value of the required query string parameter.
  	 * 
	 * @param string item The parameter whose value is required
     */		
	var param = function( item )
	{
		if ( $.isEmptyObject(parsed) )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
     */	
	var setUp = function()
	{
		parsed = parseUri();
		
		getSegments();	
	};
	
    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};
	
	return {
		
	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function( mode )
		{
			options.strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */		
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		
		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */	
		segment : function( pos )
		{
			if ( $.isEmptyObject(parsed) )
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},
		
		attr : key, // provides public access to private 'key' function - see above
		
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();
/*
$.fn.delay = function( time, name ) {

    return this.queue( ( name || "fx" ), function() {
        var self = this;
        setTimeout(function() { $.dequeue(self); } , time );
    } );

};
*/
function aerror(html,pause)
{
		if (typeof pause == "undefined") {
   			pause = 3000;
		}

		$.fancybox({'content':html});
		$('body').delay(pause).queue(function(){ $.fancybox.close(); });
		return true;
}


$(function(){
	
	/*
$("#menu > ul > li > ul").each(function(){
		var lis = $(this).find("li");
		for(var i = 0; i < lis.length; i+=5) {
		  lis.slice(i, i+5).wrapAll("<ul class='submenu_wrap'/>");
		}
	});
*/
$("#menu > ul > li > ul:has(ul) > li").each(function(){

		var lis = $(this);
		for(var i = 0; i < lis.length; i+=3) {
		  lis.slice(i, i+3).addClass("submenu_wrap2");
		}
	});
	
	
	$("#block_popular li:nth-child(1)").addClass('popular_green');
	$("#block_popular li:nth-child(2)").addClass('popular_red');
	$("#block_popular li:nth-child(3)").addClass('popular_purpure');
	
	$('#gallery li:nth-child(3n)').addClass('last');
	
	var zoom_parameters = {zoomWidth:250,zoomHeight:250}
	$(".item_photo a").eq(0).jqzoom(zoom_parameters);

	$('#gallery li a').click(function(){
		
		var thumb = $(this).find('img').eq(0).attr('big');
		$('.item_photo img').eq(0).attr('src',thumb);
		
		var big = $(this).attr('href');
		var title = $('#content h2').eq(0).text();
		$('.item_photo a').eq(0).attr('href',big);
		$('.item_photo a').eq(0).attr('title',title);
		
		$(".item_photo a").eq(0).jqzoom(zoom_parameters);
		
		return false;
	});
	$('#list_items .shop_item').equalHeight();
	// pagination
	$('.pagination .ditto_page').hide();
	$('.pagination .ditto_currentpage').next().show().next().show();
	$('.pagination .ditto_currentpage').prev().show().prev().show();
	$('.pagination .ditto_page:last, .pagination .ditto_page:first ').show();
	

	$('#content form select[name=perpage]').change(
	function(){
	
/*
	var url_query = $.url.setUrl($('form:has(select[name=perpage])').attr('action')).attr("query") ;
	
	if(typeof url_query == 'string')
	window.location = $(this).parent().attr('action')+'&perpage='+$(this).attr('value');
	else
	window.location = $(this).parent().attr('action')+'?perpage='+$(this).attr('value');
*/

		//$(this).parent().submit();
//		alert($(this).parent().attr('action')+'&perpage='+$(this).attr('value'));
		window.location = $(this).parent().attr('action')+'?perpage='+$(this).attr('value');
		
	});

	
	$('.filter_shop').each(function(){
		var filter_title = $(this).find('span').eq(0).html();
		var count_options = $(this).find('select option').size();
		if(count_options>1)
			$(this).find('select').eq(0).prepend('<option value="disabled" disabled selected>'+filter_title+'</option>');
		else
			$(this).find('select').eq(0).prepend('<option value="disabled" disabled>'+filter_title+'</option>');
		$(this).find('span').eq(0).hide();
		$(this).html($(this).html());
	});
	
	$('#shop_params > div').equalHeight();
	
	
	/*
$('#username').attr('value','Логин');
	$('#password').attr('value','Пароль');
	$('#username, #password').focus(function(){$(this).attr('value','');});
	$('#username, #password').click(function(){$(this).attr('value','');});
*/
	
	
	// SAVE Button add
	$("#save_button.noreg").click(function(){
		aerror('<p class="error_message">Доступно только для зарегистрированных</p>');
	});
	
	$('#save_button.reg').click(function(){
		var tid = $('#tovar').attr('tid');
		$.post('/user/addsave.ajax', {'tid':tid}, function(json){
            if(json.count) 
            {
            	$('#count_save').html(json.count);
            	aerror('<p class="error_message">Спасибо, товар добавлен</p>',1000);
            }
			if(json.duplicate) aerror('<p class="error_message">Этот товар есть уже в списке ваших желаний</p>',1000);
        }, 'json');                                     
  return false;
	});
	
	// SAVE list
	/*
$('.list_save .item_image').each(function(){
		var tidd = $(this).parent().attr('tid');
		$(this).prepend("<div class='item_save_delete'><a href='javascript:void(0);' tid='"+tidd+"'><img src='/js/fancybox/fancy_close.png'></a></div>");
	});
*/
	
	$(".zoom").fancybox();
	
	// SAVE Button delete
	$('.shop_item_sale a.remove').click(function(){
		var tiddd = $(this).parent().parent().attr('tid');
		var tthis = this;
		$.post('/user/deletesave.ajax', {'tid':tiddd}, function(json,tthis){
            if(json.deleted) 
            {
            	$('.shop_item_sale[tid='+json.id+']').fadeOut('slow');
            	$('#count_save').html(($('#count_save').html()-1));
            }
		}, 'json');
		return false;
	});
	
	$('.item_info').equalHeight();
	
	$('.shs-price').bind('click',function(){
		var count_no_selected = 0;
		var select_count = $('.filter_shop select').size();
		$('.filter_shop select').each(function(){
			if($(this).find('option:selected:not(:disabled)').size()>0) count_no_selected=count_no_selected+1;
		});
		if(select_count!=0 && select_count!=count_no_selected) 
		{
			$('.filter_shop select option:selected').parent().parent().addClass('error');
			aerror('<p class="error_message"><h3>Для добавления в корзину выберите размер</h3></p>',3000);
			return false;
		}
		else
		{
		$('.filter_shop').removeClass('error');
		}
		count_no_selected = 0;
	});
	
	
	$("a#fast_buy").fancybox({
		'width'				: 600,
		'height'			: 300,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});

	
	$('#cf_category label').wrap('<div class="cf_category_row"/>');
	$('#cf_category').each(function(){
	
		var lis = $(this).find("> .cf_category_row");
		var polovinka = lis.size()/2;
		for(var i = 0; i < lis.length; i+=polovinka) {
		  lis.slice(i, i+polovinka).wrapAll("<ul class='wrap'/>");
		}
	
	});
	
	$('.cf_category_row:has(input:checked)').addClass('checked');
	$('.cf_category_row').click(function(){
		$('.cf_category_row').removeClass('checked');
		$(this).addClass('checked');
		$(this).find('input[type=radio]').eq(0).change();
	});
	
	
	// other colors
	$('.othercolors').append("<div class='in_other_colors' title='Есть в других цветах' />");
	
	//$('.malo_ostalos').append("<div class='icon_malo_ostalos' title='Мало осталось' />");
	$('.icon_malo_ostalos').css({ opacity: 0.3 });
	
//	$('#DoubleTrack-5-InputMin').val('10');
//	$('#DoubleTrack-5-InputMin').val('200');
//	DoubleTrackBar.UpdateTracker(100);
	
	
	// new year
	/*

	var widow_width = $(window).width();
	var offset = $('#wrapper2').offset();
	var max_width = 1244;
	$('#wr3').css({"background-position":(Math.round(($('#wrapper2').width()+(offset.left*2)-225+100)))+'px 0'});
	if(widow_width <= max_width) 
	{ 
		$('#wr2').css({"background-position":(Math.round(offset.left-190))+'px 0'});
		
	}
	$(window).resize(function() {
  		if($(window).width() > max_width) 
  		{ 
  			$('#wr2').css({"background-position":'0 0'});
  			offset = $('#wrapper2').offset();
			$('#wr3').css({"background-position":( Math.round(($('#wrapper2').width()+(offset.left*2)-225+100)))+'px 0'});
  		}
		else {
			offset = $('#wrapper2').offset();
			$('#wr2').css({"background-position":(Math.round(offset.left-190))+'px 0'});
			$('#wr3').css({"background-position":( Math.round(($('#wrapper2').width()+(offset.left*2)-225+100)))+'px 0'});
		}
	});

*/
	

	

});


