$.fn.input_tip = function () {
	this.each(function(){
		var tip = $(this).val()

		if ($(this).attr('defValue') != undefined) {
				if ($(this).val() == ""){
					$(this).val($(this).attr('defValue'));
				}
				$(this)
					.focus(function(){
						if ($(this).val() == $(this).attr('defValue')) {
							$(this).val("")
						}
						$(this).addClass("active")
					})
					.blur(function(){
						if ($(this).val() == "") {
							$(this).val($(this).attr('defValue'))
						}
						$(this).removeClass("active")
					})
		} else {

		$(this)
			.focus(function(){
				if ($(this).val() == tip) {
					$(this).val("")
					$(this).addClass("active")
				}
			})
			.blur(function(){
				if ($(this).val() == "") {
					$(this).val(tip)
					$(this).removeClass("active")
				}
			})
		}
	});
}

$.spDebug = function() {
	var debugs = [];
	$('.spDebug').each(function(i){
		debugs.push({
				index: i,
				content: $(this).html()
			})
	})
	var markup = '<div id="debug_tabs"><ul>';
	for (d in debugs) {
		markup += '<li>'+(debugs[d].index+1)+'</li>';
	}
	markup += '</ul>';

	for (d in debugs) {
		markup += '<div id="tabs-'+(debugs[d].index+1)+'"><pre>';
		markup += debugs[d].content;
		markup += '</pre></div>';
	}
	markup += '</div>';

	$.spPopup.open({text:markup,overlay:false});
	$('#debug_tabs').css({'height':$(window).height(), 'overflow':'scroll'}).tabs();
	$('#spPopup').draggable({handle:'.spCaption'});
}

/* ========================== spPopup ==========================*/
$.spPopup = {
			plugin: this,
			css3: !(($.browser.msie === true) && (parseInt($.browser.version)<9)),
			isIe: $.browser.msie,
			open: function(params){
				var defaults = {
					title:'Сообщение от Sapato.ru',
					overlay:true,
					overlayClose:false,
					position:'middle'
				}

				var params = $.extend(defaults, params);

				if ($('#spPopup').size() === 0) {
					if (typeof params !== 'undefined') {

						var popup = "\
<noindex>\
<table border='0' cellspacing='0' cellpadding='0' style='' cols='3'>\
	<tr class='spCaption'>\
		<td class='spLft'>&nbsp;</td>\
		<td class='spMdl'>\
			<div class='spClose'></div>\
			<div class='spTitle'><nobr>"+params.title+"</nobr></div></td>\
		<td class='spRt'>&nbsp;</td>\
	</tr>\
	<tr class='spBody'>\
		<td class='spLft'>&nbsp;</td>\
		<td class='spMdl'>\
			<div class='spPopupContent'>\
			</div>\
		</td>\
		<td class='spRt'>&nbsp;</td>\
	</tr>\
	<tr class='spBottom'>\
		<td class='spLft'>&nbsp;</td>\
		<td class='spMdl'>&nbsp;</td>\
		<td class='spRt'>&nbsp;</td>\
	</tr>\
</table>\
</noindex>";

						var spPopup = $("<div id='spPopup' />").appendTo($('body')).css({'display':'none'});
						spPopup.html(popup);
						var spPopupContent = $('.spPopupContent',spPopup);
						//var spPopupClose = $('<a class="spPopupClose" />').appendTo(spPopup);

//						spPopupClose.click(function(){
	//						$.spPopup.close(spPopup);
		//				});

						$(document).keyup(function(evt){
							if (evt.which == 27) {
								$.spPopup.close(spPopup);
							}
						});

						var $spClose = $('.spClose',spPopup);
						$spClose.click(function(){
							$.spPopup.close(spPopup);
						});

						if (params.overlay !== false) {
							var spPopupOverlay = $('<div id="spPopupOverlay" />').appendTo($('body')).css('opacity',0);
							spPopupOverlay.animate({opacity:.7},{duration:400,queue:false});
						}

						if (typeof params.width !== 'undefined') {
								spPopupContent.css('width',params.width+'px');
							}

						var spPopupShow = function(){
							if (!css3) {
								spPopup.show();
							} else {
								spPopup.css({'opacity':0,'display':'block'});
								spPopup.find('.spBody .spMdl').width(spPopup.find('.spBody .spMdl').width());
								spPopup.animate({opacity:1},{duration:400,queue:false});
							}

							if ((typeof params.drag !='undefined') & (params.drag != false)) {spPopup.draggable({handle:'.spCaption .spTitle'})};

							if (typeof(params.successFunc) !== 'undefined') {
								if ($.isFunction(params.successFunc)) {
									params.successFunc();
								}
							}
						}

						if (typeof params.url !== 'undefined') {
							spPopupContent.load(params.url,function(){
								$.spPopup.reposition(spPopup,params.position);
								params.type = 'url';
								spPopupShow();
							});
						} else if (typeof params.text !== 'undefined') {
							spPopupContent.html(params.text);
							spPopup.css({'display':'block','opacity':0});
							var spPopupWidth = spPopupContent.width();
							spPopup.removeAttr('style');
							$('.spTitle',spPopup).width(Math.max(spPopupWidth,300));
							$.spPopup.reposition(spPopup,params.position);
							params.type = 'text';
							spPopupShow();
						} else if ((typeof params.dom !== 'undefined') && ($(params.dom).size()>0)) {
							var $domClone = $(params.dom).clone(true);
							$domClone.removeAttr('id');
							spPopupContent.append($domClone);
							$domClone.css({'display':'block'});
							$.spPopup.reposition(spPopup,params.position);
							spPopupShow();
						} else if (typeof params.image !== 'undefined') {
							var img = new Image();
							var dW = $(document).width();
							var wH = $(window).height();
							$(img).load(function(){
								var imgSize = {'width':this.width,'height':this.height};
								$(this).appendTo(spPopupContent);
								var tHeight = Math.min(wH-50,imgSize.height);
								var tWidth = (imgSize.width*tHeight)/imgSize.height;
								$(this).css({'height': tHeight,'width':tWidth});
								$.spPopup.reposition(spPopup,params.position);
								spPopupShow();
							}).attr('src',params.image);
							params.type = 'image';
						} else if (typeof params.video !== 'undefined') {
								var videoHref = params.video;
								var contWidth = typeof(params.width)!='undefined' ? params.width:450,
										contHeight = typeof(params.height)!='undefined' ? params.height:325;

								var $videoMarkup = "\
<div id='videoBlock' style='text-align:center; width:"+(contWidth+20)+"px; height:"+contHeight+"px;'>\
	<object width='"+contWidth+"' height='"+contHeight+"' id='flvPlayer' style='margin:0 auto;'>\
		<param name='allowFullScreen' value='true'>\
		<param name='allowScriptAccess' value='always'>\
		<param name='movie' value='/flash/OSplayer.swf?movie="+videoHref+"&btncolor=0x333333&accentcolor=0x888888&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=on&showTitle=no'>\
		<embed src='/flash/OSplayer.swf?movie="+videoHref+"&btncolor=0x333333&accentcolor=0x888888&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=on&showTitle=no' width='"+contWidth+"' height='"+contHeight+"' allowFullScreen='true' type='application/x-shockwave-flash' allowScriptAccess='always'>\
	</object>\
</div>";
								spPopupContent.html($videoMarkup);
								$.spPopup.reposition(spPopup,params.position);
								params.type = 'video';
								spPopupShow();
						} else {
							spPopupContent.html('Неизвестная ошибка!');
							$.spPopup.reposition(spPopup,params.position);
							spPopupShow();
						}

						if (typeof params.autoclose == 'number') {
							var autoclose = setTimeout(function(){$.spPopup.close(spPopup);},params.autoclose*1000);
						}

						if ((typeof spPopupOverlay !== 'undefined')&&(params.overlayClose == true)) {
							spPopupOverlay.click(function(){$.spPopup.close(spPopup)});
						}

						spPopup.data('params',params);

					}
				}
				return spPopup;
			},
			close:function(popup, callBack){
				var spPopup = popup;
				if ((spPopup.data('params').type != undefined) & (spPopup.data('params').type == 'video')) {
					var spPopupContent = $('.spPopupContent',spPopup);
					spPopupContent.width(spPopupContent.width());
					spPopupContent.height(spPopupContent.height());
					$('#videoBlock',spPopup).remove();
				}
				if (css3) {
					spPopup.animate({opacity:0},
						{duration:400,
						queue:false,
						complete:function(){
										if (typeof spPopup.data('params').closeCallback != 'undefined') {
											spPopup.data('params').closeCallback();
										}
										spPopup.remove();
										spPopup = undefined;
										if (typeof callBack === 'function') {
											callBack();
										}
								}
						})
				} else {
					spPopup.hide();
					if (typeof spPopup.data('params').closeCallback != 'undefined') {
						spPopup.data('params').closeCallback();
					}
					spPopup.remove();
					spPopup = undefined;
					if (typeof callBack === 'function') {
						callBack();
					}
				}
				var spPopupOverlay = $('#spPopupOverlay');
				if (spPopupOverlay.size()>0) {
					spPopupOverlay.animate({opacity:0},
						{duration:400,
						queue:false,
						complete:function(){
											spPopupOverlay.remove();
								}
						})
				}
			},

			reposition:function(popup,position){
				var scrolltop = $(window).scrollTop();
				var spPopupY = 0,
						spPopupX = 0;
				switch(position){
				case 'top':
					spPopupY = 50;
					spPopupX = (($(document).width() / 2) - (popup.width()/2));
					break;
				case 'bottom':
					if (popup.height() > $(window).height()) {
						spPopupY = 50;
					} else {
						spPopupY = $(window).height() - popup.height() - 50;
					}
					spPopupX = (($(document).width() / 2) - (popup.width()/2));
					break;
				case 'br':
					if (popup.height() > $(window).height()) {
						spPopupY = 50;
					} else {
						spPopupY = $(window).height() - popup.height() - 50;
					}
					spPopupX = 20;
					break;
				default:
					if (popup.height() > $(window).height()) {
						spPopupY = 50;
					} else {
						spPopupY = $(window).height()/2 - popup.height()/2;
					}
					spPopupX = (($(document).width() / 2) - (popup.width()/2));

				}
				if (position != 'br') {
					popup.css({
						'top':scrolltop+spPopupY+'px',
						'left':spPopupX+'px'
					});
				} else {
					popup.css({
						'top':scrolltop+spPopupY+'px',
						'right':spPopupX+'px',
						'left':'auto'
					});
				}
			}
}
/* ===================== /end spPopup ====================== */

/* ===================== spLoading ===================== */
$.fn.spLoading = function(params){

	var defaults = {
			action:'start',
			delay:2000
		};

	var params = $.extend(defaults, params);

	return this.each(function(){
		var obj = $(this);

		if (obj.data('spLoading') == true) {
			params.action = 'stop';
			var overlay = $('.spLoading',obj);
		} else {
			var overlay = $('<div class="spLoading" />');
		}

		if (this.nodeName.toLowerCase() == 'body') {
			overlay.css('position','fixed');
		}

		switch(params.action){
		case 'stop':
			clearTimeout(delay);
			obj.removeData('spLoading');
			obj.removeData('preventLoader');
			overlay.animate({'opacity':0},{duration:200,queue:false,complete:function(){$(this).remove();}})
			break;
		default:
			obj.data('spLoading',true);
			if (obj.data('preventLoader') != true) {
				delay = setTimeout(function(){
						var loader = $('<img src="/images/loader3d.gif" width="48" height="32" alt="Загрузка..." />');
						overlay.appendTo(obj);
						loader.appendTo(overlay);
						loader.css({'left':overlay.width()/2 - loader.width()/2,'top':overlay.height()/2 - loader.height()/2});
						overlay.animate({'opacity':0.7},{duration:200,queue:false})
				},params.delay);
			} else {obj.removeData('preventLoader');}
		}
	})
}

$.fn.spContentSlider = function(progressTracker,step){
	return this.each(function(){
		curStep=0;
		var contentSlider = $(this);
		var steps = $(this).children('.spStep');
		var stepCount = steps.size();
		var curWidth = $(this).width();

		if (typeof step !== 'undefined') {
			var spGotoStep = function(step){
				curStep = step;
				contentSlider.animate({'margin-left':-curStep*curWidth+'px'},{duration:300,queue:false})
				var curProgressTracker = $('.'+progressTracker);
				curProgressTracker.children('li').each(function(){$(this).removeClass('active')});
				$(curProgressTracker.children('li').get(curStep)).addClass('active');
			}

			spGotoStep(step);
			return this;
		}

		steps.each(function(){
				$(this).width(curWidth);
		})

		$(this).width(curWidth * stepCount);

		var spNextStep = function(){
			if (curStep < stepCount-1) {
				curStep++;
				contentSlider.animate({'margin-left':-curStep*curWidth+'px'},{duration:300,queue:false})
				var curProgressTracker = $('.'+progressTracker);
				curProgressTracker.children('li').each(function(){$(this).removeClass('active')});
				$(curProgressTracker.children('li').get(curStep)).addClass('active');
			}
		}

		var spPrevStep = function(){
			if (curStep > 0) {
				curStep--;
				contentSlider.animate({'margin-left':-curStep*curWidth+'px'},{duration:300,queue:false})
				var curProgressTracker = $('.'+progressTracker);
				curProgressTracker.children('li').each(function(){$(this).removeClass('active')});
				$(curProgressTracker.children('li').get(curStep)).addClass('active');
			}
		}

		steps.find('.next_step').click(function(evt){evt.preventDefault(); spNextStep()});
		steps.find('.prev_step').click(function(evt){evt.preventDefault(); spPrevStep()});
	})
}


/* ===================== spProgressTracker =====================*/
$.progressTracker = function(element, options) {

	/*
	options:
		stepCount: integer,
		stepLabelType: string - none, numeral or text
		labels: array of strings

	EXAMPLE:
		$('#prog').progressTracker({stepCount:5, stepLabels:['one','two','three',4,5,6,'seven','eight']})
		$('#prog').data('progressTracker').gotoStep(6)

	*/

	var defaults = {
		stepCount: 3,
		stepLabelType: 'numeral' // none, numeral, text
	}

	var plugin = this;
	plugin.curStep = 1;
	plugin.settings = {}

	var $element = $(element),
		 element = element;

	plugin.init = function() {
		$element.css({'overflow':'hidden','text-align':'center'});

		plugin.settings = $.extend({}, defaults, options);

		if ((typeof plugin.settings.stepLabels !== 'undefined') && (plugin.settings.stepLabels.length > 0)) {
			plugin.settings.stepLabelType = 'text';
		}

		if ((plugin.settings.stepLabelType == 'text') || ((typeof plugin.settings.stepLabels !== 'undefined') && (plugin.settings.stepLabels.length > 0))) {
				plugin.settings.stepCount = plugin.settings.stepLabels.length;
		}

		// Form HTML code of the progress tracker
		var tempHTML = '<ul class="progressTracker">\n';
		for (var i = 0; i<plugin.settings.stepCount; i++) {
			tempHTML += '<li>';
			if (plugin.settings.stepLabelType == 'numeral') {
				tempHTML += '<span class="num">'+(i+1)+'</span>';
			} else if (plugin.settings.stepLabelType == 'text') {
				tempHTML += '<span>'+plugin.settings.stepLabels[i]+'</span>';
			}
			tempHTML += '</li>\n';
		}
		tempHTML += '</ul>';

		$element.html(tempHTML);
		$element.find('li').not(':last').width($element.width()/(plugin.settings.stepCount-1)-100);
		if (plugin.settings.stepLabelType == 'text') {
			$element.find('li span').each(function(){
				$(this).css('margin-left',-$(this).width()/2+10)
			})
		}
		$element.find('ul').width(
			function(){
				var sumW = 0;
				$element.find('li').each(function(){sumW += $(this).width();})
				return sumW;
			}
		).css('margin','0 auto');

		plugin.gotoStep(1);
	}

	plugin.gotoStep = function(step) {
		if ((step > 0)&&(step <= plugin.settings.stepCount)) {
			plugin.curStep = step;
			$element.find('li:gt('+(step-1)+')').removeClass();
			$element.find('li:lt('+(step)+')').not(':first, :last').removeClass().addClass('finished');
			$element.find('li:nth-child('+(step)+')').removeClass().addClass('active')

			if (step>1) {
				$element.find('li:first').removeClass().addClass('step1_f')
			} else {
				$element.find('li:first').removeClass().addClass('step1_a')
			}

			if (step < plugin.settings.stepCount) {
				$element.find('li:last').removeClass().addClass('stepLast')
			} else {
				$element.find('li:last').removeClass().addClass('stepLast_a')
			}
			return plugin.curStep;
		} else {
			return false;
		}
	}

	plugin.nextStep = function() {
		if (plugin.curStep+1 <= plugin.settings.stepCount) {
			plugin.gotoStep(plugin.curStep+1);
			return plugin.curStep;
		} else {
			return false;
		}
	}

	plugin.prevStep = function() {
		if (plugin.curStep-1 >= 1) {
			plugin.gotoStep(plugin.curStep-1);
			return plugin.curStep;
		} else {
			return false;
		}
	}

	plugin.init();

}

$.fn.progressTracker = function(options) {

	return this.each(function() {
		if (undefined == $(this).data('progressTracker')) {
			var plugin = new $.progressTracker(this, options);
			$(this).data('progressTracker', plugin);
		}
	});

}
/* ===================== /end spProgressTracker =====================*/


$(document).ready(function(){
	css3 = !(($.browser.msie === true) && (parseInt($.browser.version)<9));

	if (typeof $.fn.autocomplete == 'function') {
		var ac_options = {
			minChars: 1,
			multiple: true,
			multipleSeparator: ' ',
			matchContains: true,
			matchCase: false,
			autoFill: false,
			scrollHeight: 220
		};

		if ($('#autocomplete').size()<1) {
			$.post('/scripts/ajax/autocomplete.php',function(data){
				var db = data.split(',');
				$('.search_input').autocomplete(db,ac_options);
			});
		} else {
			var db = $('#autocomplete').text().split(',');
			$('.search_input').autocomplete(db,ac_options);
		}

	}

	$('a.btnQuickCheckout.QCOld').click(function(evt){
			evt.preventDefault();
			var target = $(evt.currentTarget);
			var prodID = '';
			if (target.attr('rel')=='nofollow') {
				prodID = target.attr('href');
				prodID = prodID.match(/\d+/)[0];
			} else {
				prodID = target.attr('rel');
			}
			/*$.spPopup.open({url:'/scripts/ajax/popup/checkOut02.php?id='+prodID,
							successFunc:function(){
								$('.spContentSlider').spContentSlider('progress_tracker');

								var available_sized = $("#detail_size li.available");

								available_sized.click(function(){
									available_sized.removeClass("active");
									size_selected = $(this).attr("name");
									$(this).addClass("active");
									$('.size_not_selected').css('display','none');
								})
							}
						}
		)*/
		$.spPopup.open({url:'/scripts/ajax/popup/main_quick_view.php?id='+prodID,
							successFunc:function(){
								$('.spContentSlider').spContentSlider('progress_tracker');

								var available_sized = $("#detail_size li.available");

								available_sized.click(function(){
									available_sized.removeClass("active");
									size_selected = $(this).attr("name");
									$(this).addClass("active");
									$('.size_not_selected').css('display','none');
								})
							}
						}
		)
	});


	$(".search_input").input_tip()
	$(".basket-coupon input[name=COUPON]").input_tip()

	$("div.subs_input #sf_EMAIL").input_tip()
	$(".subscription_box input[type='text']").input_tip()
	$(".forum-reply-field-author #REVIEW_AUTHOR").input_tip()

	var top_menu_items = $("#menu_box > div.menu_top_item")
	top_menu_items
		.mouseenter(function(){
			top_menu_items.addClass("inactive")
			$(this).removeClass("inactive")
		})
		.mouseleave(function(){
			top_menu_items.removeClass("inactive")
		})

	$('.site_mode a:not(.active)').hover(
    function(evt){
      $(evt.currentTarget).animate({left:-10},{duration:100,queue:false});
    },
    function(evt){
      $(evt.currentTarget).animate({left:-14},{duration:100,queue:false});
    }
  )

	var tabs = $(".tabs > div")
	var	tabs_content = $(".tabs_content > div")
	tabs
		.click(function(){
			tabs.removeClass("active")
			$(this).addClass("active")
			for (var i = 0, item;  item = tabs[i]; i++ ) {
				if ($(item).hasClass("active")) {
					$(tabs_content).addClass("inactive")
					$(tabs_content[i]).removeClass("inactive")
				}
			}
		})


/*	$("div.main_catalog_item_box, div.last_seen_item_box").click(function(e){

		var link

		function gogo() {
			document.location.href = link.attr("href")
		}

		link = $("div.item_image_box a",this)
		link.click(function(e){
			gogo()
			e.stopPropagation()
		})

		$("div.item_info_box a",this).click(function(e){
			gogo()
			e.stopPropagation()
			return false
		})

		gogo()
		e.stopPropagation()

	})
*/
	if ($.browser.msie) {

		$("div.top_sellers_item img").click(function(e){

			var link

			function gogo() {
				document.location.href = link.attr("href")
			}

			link = $(this).parents("a")

			gogo()
			e.stopPropagation()
		})
	}

	/*
		попап на размеры
	*/
	$("a.to-table-of-sizes").live("click",function(){
		window.open($(this).attr("href"), "popsize","width=650,height=550,left=300,top=200,location=no,menubar=no,status=no,toolbar=no,resizable=yes,scrollbars=yes");
		return false
	})
	/*
		попап на доставку
	*/
	$("a.to-delivery").live("click",function(evt){
		evt.preventDefault();
		$.spPopup.open({
				url:'https://www.sapato.ru/service/delivery/index.php #main_head .padding-box',
				successFunc:function(){
					$.getScript(
							'http://www.sapato.ru/service/delivery/script.js',
							function(){init_delivery_info()}
					)
				},
				width: 900
		});
	});

	var ci = $(".captcha_image")
	ci.after($("<a>").attr({"href":"#","title":"Нажмите, если не видите картинку","class":"captcha-reload"}).html("Не видите картинку?").click(function(){
		var c = ci.attr("src") + "&" + Math.round(Math.random(1,999));
		ci.attr("src",c);
		return false;
	}))


	$("#offer").live("click",function(){
		if ($(this).is(":checked")) {
			setCookie("offerta",true)
			$("button[name='qs_submits']").children('div').removeClass().addClass('btn_a');
			$(".checkout_terms, .checkout_terms_corner").hide();
		} else {
			setCookie("offerta",false)
			$("button[name='qs_submits']").children('div').removeClass().addClass('btn_d');
			$(".checkout_terms, .checkout_terms_corner").show();
		}
	})

	$('div.abc a').click(function(evt){
		evt.preventDefault();
		var curLetter = $(this).attr('class');
		var curDiv = $('.brand_list_col .'+curLetter);
		$(window).scrollTop(curDiv.offset().top-15);
	})

	//$("#inner_rightcol, #main_leftcol").height($("#main_head").height()-2);
})


//$(window).load(function(){
//$("#inner_rightcol, #main_leftcol").height($("#main_head").height()-2);
//})


function catalog_link(params) {

	if (!params) return false

	if (params["search"]) {
		result = "/search/";
	} else {
		result = "/catalog/";
	}


	if (params["man"]) {
		result = result + "man/"
	}
	else if (params["woman"]) {
		result = result + "woman/"
	}
	else if (params["kid"]) {
		result = result + "kid/"
	}


	if (params["new"]) {
		result = result + "news/"
	} else if (params["sale"]) {
		result = result + "sales/"
	} else if (params["brand"] && !params["brand_id"]) {
		result = result + "brand/"
	}

	if (params["section"] > 0) {
		result = result + params["section"] + "/"
	}

	if (params["brand_id"] && params["brand"]) {
		result = result + "brand/" + params["brand_id"] + "/"
	}


	if (params["sort"]) {
		result = result + params["sort"] + "/"
	}

	if (params["page"] > 0) {
		result = result + params["page"] + "/"
	} else {
		result = result + "page/1/"
	}

	if (params["search"]) {
		if (params["how"] == "d") {
			result = result + "date/"
		} else {
			result = result + "rank/"
		}
		result = result + "?q=" + params["search"];
	}
	return result
}
function setCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
            ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
            ( ( path ) ? ";path=" + path : "" ) +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ( ( secure ) ? ";secure" : "" );
}
function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ))
    return matches ? decodeURIComponent(matches[1]) : undefined
}
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/*
$.fn.validates_presence = function() {
	var error_class = ""
	if ($(this).val() == "") {
		$(this).set_invalid()
		return false;
	} else {
		$(this).set_valid()
		return true;
	}
}

$.fn.set_invalid = function() {
	$(this).addClass("validate-error")
}

$.fn.set_valid = function() {
	$(this).removeClass("validate-error")
}

$(document).ready(function() {
	$('form').submit(function() {
		var valid = true;
		$("input[validate='presence']", $(this)).each(function(index) {
		  if ($(this).validates_presence() == false) {
				valid = false;
		  }
		});
		return valid;
	});
});
*/

/************** подключаем события ClickTale ***************/

function convert2EN(from)  {
var rusChars = new Array(' ', 'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ч','ц','ш','щ','э','ю','\я','ы','ъ','ь', ' ', '\'', '\"', '\#', '\$', '\%', '\&', '\*', '\,', '\:', '\;', '\<', '\>', '\?', '\[', '\]', '\^', '\{', '\}', '\|', '\!', '\@', '\(', '\)', '\-', '\=', '\+', '\/', '\\');
var transChars = new Array('_', 'a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f','h','ch','c','sh','csh','e','ju','ja','y','', '', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
  from = from.toLowerCase();
  var to = "";
  var len = from.length;
  var character, isRus;
  for(var i=0; i < len; i++)
    {
    character = from.charAt(i,1);
    isRus = false;
    for(var j=0; j < rusChars.length; j++)
      {
      if(character == rusChars[j])
        {
        isRus = true;
        break;
        }
      }
    to += (isRus) ? transChars[j] : character;
    }
   return to;
  }

$(document).ready(function(){
	$(".clicktale").click(function(){
	var text = '';
	if($(this).text() && $(this).text().length > 2) text  = $(this).text();
	else{
		if($(this).attr("title")) text = $(this).attr("title");
		else { if ($(this).text()) text = $(this).text();
				else text = 'unknown';

		}
	}
		if (typeof(ClickTaleTag)== 'function') ClickTaleTag(convert2EN(text));
	})


	/* Вызов Popup Windows с видео */

		$(window).bind("load", function() { 				// запускаем скрипт, лишь после полной загрузки окна
	   		var p_url=location.search.substring(1); 		// получаем строку запроса
			var parametr=p_url.split("&"); 					// получаем параметры

			var params= new Array();
			for(i in parametr) {
			    var j=parametr[i].split("="); 				// разделяем параметры
			    params[j[0]]=unescape(j[1]);
			}

			if (params['play'] == 'go') { 					// если запрос на проигрывание видео
				$("li.video > a > img").click();  			// эмулируем нажатие на видео
			}
			// наслаждаемся результатом
		});
});

/***********************************************************/

function ajaxGetPersonalMenu(){
	$.ajax({
		url: '/scripts/ajax/ajax_personal_menu.php',
		success: function (data) {
			$('.personal_menu').first().html(data);
		},
		error: function (jqXHR, exception) {
			if (jqXHR.status === 0) {
				console.log('Not connect.\n Verify Network.');
			} else if (jqXHR.status == 404) {
				console.log('Requested page not found. [404]');
			} else if (jqXHR.status == 500) {
				console.log('Internal Server Error [500].');
			} else if (exception === 'parsererror') {
				console.log('Requested JSON parse failed.');
			} else if (exception === 'timeout') {
				console.log('Time out error.');
				ajaxGetPersonalMenu();
			} else if (exception === 'abort') {
				console.log('Ajax request aborted.');
				ajaxGetPersonalMenu();
			} else {
				console.log('Uncaught Error.\n' + x.responseText);
			}
		}
	});
}
function ajaxGetPersonalBasket() {
	$.ajax({
		url: '/scripts/ajax/ajax_small_basket.php',
		success: function (data) {
			$('#header_cart').html(data);
		},
		error: function (jqXHR, exception) {
			if (jqXHR.status === 0) {
				console.log('Not connect.\n Verify Network.');
			} else if (jqXHR.status == 404) {
				console.log('Requested page not found. [404]');
			} else if (jqXHR.status == 500) {
				console.log('Internal Server Error [500].');
			} else if (exception === 'parsererror') {
				console.log('Requested JSON parse failed.');
			} else if (exception === 'timeout') {
				console.log('Time out error.');
				ajaxGetPersonalBasket();
			} else if (exception === 'abort') {
				console.log('Ajax request aborted.');
				ajaxGetPersonalBasket();
			} else {
				console.log('Uncaught Error.\n' + x.responseText);
			}
		}
	});
}

function plural($n, $form1, $form2, $form3) {

	if (($n % 10 == 1) && ($n % 100 != 11)) {
		$plural = 0;
	} else {
		if (($n % 10 >= 2) && ($n % 10 <= 4) && (($n % 100 < 10) | ($n % 100 >= 20))) {
			$plural = 1;
		} else {
			$plural = 2;
		}
	}
	switch ($plural) {
		case 0:
		default:
			return $form1;
		case 1:
			return $form2;
		case 2:
			return $form3;
	}
}

$(window).bind("load", function() {

	//$("#vote_radio_20_76").click(function() {
	//			$(".btn_invis").css({'display': 'block' });
	//		});



	var p_url=location.search.substring(1); 		// получаем строку запроса
			var parametr=p_url.split("&"); 					// получаем параметры

			var params= new Array();
			for(i in parametr) {
			    var j=parametr[i].split("="); 				// разделяем параметры
			    params[j[0]]=unescape(j[1]);
			}

			if ((params['VOTE_ID'] == 2) && (params['VOTE_SUCCESSFULL'] == 'Y')) {
				$.spPopup.open({url:'/scripts/ajax/popup/vote_thanks.php',
					successFunc:function(){
						$('.spContentSlider').spContentSlider('progress_tracker');
					}
				})
			}


	function code_check() {
		//alert(2);

		$('#code_mobile_phone_input_name').live('change', function() {
			var codeFirstInt = $(this).val().substr(0,1);

			if (codeFirstInt != 9) {
				$(".code_tel").first().html( $(".code_tel").html() + "<span class='mess' style=''>Код должен начинаться с '9'</span>" );
				$(".mess").slideToggle("slow");
				$("#code_mobile_phone_input_name").val("");
				$(".mess").slideToggle("slow");

			}

			var k = 1;
		});
	}

	setTimeout(code_check,2);

$('#weather').click(function() {
				window.location.href = '/weather/';
				document.body.style.cursor = 'wait';
	});
			
	$('#quick_buy').click(function() {
				window.location.href = '/service/ipad/';
				document.body.style.cursor = 'wait';
	});
	
	$('#e-gift').click(function() {
				window.location.href = '/sapato/e-gift/';
				document.body.style.cursor = 'wait';
	});
	
	$('.e-gift').click(function() {
				window.location.href = '/sapato/e-gift/';
				document.body.style.cursor = 'wait';
	});
	
	$('#online_help').click(function() {
				//window.location.href = 'http://zingaya.com/widget/c4d87036facda92ceb07a6d4df2fd404';
				window.open('http://zingaya.com/widget/c4d87036facda92ceb07a6d4df2fd404?referrer='+escape(window.location.href), '_blank', 'width=236,height=220,resizable=no,toolbar=no,menubar=no,location=no,status=no');
				document.body.style.cursor = 'wait';
	});




});
