
/*!
 * site functions 
 */

/*!
 * jQuery Tools dev - The missing UI library for the Web
 * 
 * overlay/overlay.js
 * toolbox/toolbox.expose.js
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 */
(function(a){a.tools=a.tools||{version:"dev"},a.tools.overlay={addEffect:function(a,b,d){c[a]=[b,d]},conf:{close:null,closeOnClick:!0,closeOnEsc:!0,closeSpeed:"fast",effect:"default",fixed:!a.browser.msie||a.browser.version>6,left:"center",load:!1,mask:null,oneInstance:!0,speed:"normal",target:null,top:"10%"}};var b=[],c={};a.tools.overlay.addEffect("default",function(b,c){var d=this.getConf(),e=a(window);d.fixed||(b.top+=e.scrollTop(),b.left+=e.scrollLeft()),b.position=d.fixed?"fixed":"absolute",this.getOverlay().css(b).fadeIn(d.speed,c)},function(a){this.getOverlay().fadeOut(this.getConf().closeSpeed,a)});function d(d,e){var f=this,g=d.add(f),h=a(window),i,j,k,l=a.tools.expose&&(e.mask||e.expose),m=Math.random().toString().slice(10);l&&(typeof l=="string"&&(l={color:l}),l.closeOnClick=l.closeOnEsc=!1);var n=e.target||d.attr("rel");j=n?a(n):null||d;if(!j.length)throw"Could not find Overlay: "+n;d&&d.index(j)==-1&&d.click(function(a){f.load(a);return a.preventDefault()}),a.extend(f,{load:function(d){if(f.isOpened())return f;var i=c[e.effect];if(!i)throw"Overlay: cannot find effect : \""+e.effect+"\"";e.oneInstance&&a.each(b,function(){this.close(d)}),d=d||a.Event(),d.type="onBeforeLoad",g.trigger(d);if(d.isDefaultPrevented())return f;k=!0,l&&a(j).expose(l);var n=e.top,o=e.left,p=j.outerWidth({margin:!0}),q=j.outerHeight({margin:!0});typeof n=="string"&&(n=n=="center"?Math.max((h.height()-q)/2,0):parseInt(n,10)/100*h.height()),o=="center"&&(o=Math.max((h.width()-p)/2,0)),i[0].call(f,{top:n,left:o},function(){k&&(d.type="onLoad",g.trigger(d))}),l&&e.closeOnClick&&a.mask.getMask().one("click",f.close),e.closeOnClick&&a(document).bind("click."+m,function(b){a(b.target).parents(j).length||f.close(b)}),e.closeOnEsc&&a(document).bind("keydown."+m,function(a){a.keyCode==27&&f.close(a)});return f},close:function(b){if(!f.isOpened())return f;b=b||a.Event(),b.type="onBeforeClose",g.trigger(b);if(!b.isDefaultPrevented()){k=!1,c[e.effect][1].call(f,function(){b.type="onClose",g.trigger(b)}),a(document).unbind("click."+m).unbind("keydown."+m),l&&a.mask.close();return f}},getOverlay:function(){return j},getTrigger:function(){return d},getClosers:function(){return i},isOpened:function(){return k},getConf:function(){return e}}),a.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}}),i=j.find(e.close||".close"),!i.length&&!e.close&&(i=a("<a class=\"close\"></a>"),j.prepend(i)),i.click(function(a){f.close(a)}),e.load&&f.load()}a.fn.overlay=function(c){var e=this.data("overlay");if(e)return e;a.isFunction(c)&&(c={onBeforeLoad:c}),c=a.extend(!0,{},a.tools.overlay.conf,c),this.each(function(){e=new d(a(this),c),b.push(e),a(this).data("overlay",e)});return c.api?e:this}})(jQuery);
(function(a){a.tools=a.tools||{version:"dev"};var b;b=a.tools.expose={conf:{maskId:"exposeMask",loadSpeed:"slow",closeSpeed:"fast",closeOnClick:!0,closeOnEsc:!0,zIndex:9998,opacity:.8,startOpacity:0,color:"#fff",onLoad:null,onClose:null}};function c(){if(a.browser.msie){var b=a(document).height(),c=a(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,b-c<20?c:b]}return[a(document).width(),a(document).height()]}function d(b){if(b)return b.call(a.mask)}var e,f,g,h,i;a.mask={load:function(j,k){if(g)return this;typeof j=="string"&&(j={color:j}),j=j||h,h=j=a.extend(a.extend({},b.conf),j),e=a("#"+j.maskId),e.length||(e=a("<div/>").attr("id",j.maskId),a("body").append(e));var l=c();e.css({position:"absolute",top:0,left:0,width:l[0],height:l[1],display:"none",opacity:j.startOpacity,zIndex:j.zIndex}),j.color&&e.css("backgroundColor",j.color);if(d(j.onBeforeLoad)===!1)return this;j.closeOnEsc&&a(document).bind("keydown.mask",function(b){b.keyCode==27&&a.mask.close(b)}),j.closeOnClick&&e.bind("click.mask",function(b){a.mask.close(b)}),a(window).bind("resize.mask",function(){a.mask.fit()}),k&&k.length&&(i=k.eq(0).css("zIndex"),a.each(k,function(){var b=a(this);/relative|absolute|fixed/i.test(b.css("position"))||b.css("position","relative")}),f=k.css({zIndex:Math.max(j.zIndex+1,i=="auto"?0:i)})),e.css({display:"block"}).fadeTo(j.loadSpeed,j.opacity,function(){a.mask.fit(),d(j.onLoad),g="full"}),g=!0;return this},close:function(){if(g){if(d(h.onBeforeClose)===!1)return this;e.fadeOut(h.closeSpeed,function(){d(h.onClose),f&&f.css({zIndex:i}),g=!1}),a(document).unbind("keydown.mask"),e.unbind("click.mask"),a(window).unbind("resize.mask")}return this},fit:function(){if(g){var a=c();e.css({width:a[0],height:a[1]})}},getMask:function(){return e},isLoaded:function(a){return a?g=="full":g},getConf:function(){return h},getExposed:function(){return f}},a.fn.mask=function(b){a.mask.load(b);return this},a.fn.expose=function(b){a.mask.load(b,this);return this}})(jQuery);


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

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;
};

function showComment (controlId) {
	var control = document.getElementById(controlId); 
	control.checked = true;
	control.blur();
	var clazzName = controlId.substring(0,controlId.length-1);
	if(controlId == 'deliv1') {
		document.getElementById('deliveryAddress').style.display = 'block';
		document.getElementById('deliveryAddresTextarea').style.display = '';
	} else if(clazzName == 'deliv') {
		document.getElementById('deliveryAddress').style.display = 'none';
		document.getElementById('deliveryAddresTextarea').style.display = 'none';
	}
	var comments = getElementsByClass(clazzName + "LabelComment",document.getElementById('"orderFormBlock"'),"P");
	for (var i = 0; i < comments.length; i++) {
		var commentLabel = comments[i];
		if (commentLabel.id.indexOf(controlId) >= 0) {
			commentLabel.style.display = 'block';
		} else {
			commentLabel.style.display = 'none';
		} 
	}
}


function showHelpTip(e, sHtml, bHideSelects, mouseOutHidden) {
	// find anchor element
	//alert(sHtml);
	var el = e.target || e.srcElement;
	while (el.tagName != "A")
		el = el.parentNode;
	
	// is there already a tooltip? If so, remove it
	if (el._helpTip) {
		helpTipHandler.hideHelpTip(el);
	}
	
	helpTipHandler.hideSelects = Boolean(bHideSelects);
	
	// create element and insert last into the body
	helpTipHandler.createHelpTip(el, sHtml);
	
	// position tooltip
	helpTipHandler.positionToolTip(e);
	
	// add a listener to the blur event.
	// When blurred remove tooltip and restore anchor
	el.onblur = helpTipHandler.anchorBlur;
	el.onkeydown = helpTipHandler.anchorKeyDown;
	if (mouseOutHidden) {
		el.onmouseout = helpTipHandler.anchorMouseOut;
	}
	
}

var helpTipHandler = {
	hideSelects: false,
	
	helpTip: null,
	
	showSelects: function (bVisible) {
		if (!this.hideSelects) return;
		// only IE actually do something in here
		var selects = [];
		if (document.all)
			selects = document.all.tags("SELECT");
		var l = selects.length;
		for (var i = 0; i < l; i++)
			selects[i].runtimeStyle.visibility = bVisible ? "" : "hidden";
	},

	create: function () {
		var d = document.createElement("DIV");
		d.className = "help-tooltip";
		d.onmousedown = this.helpTipMouseDown;
		d.onmouseup = this.helpTipMouseUp;
		var placeholder = document.getElementById("tooltipPlaceholder");
		if (placeholder) {
			document.body.replaceChild(d, document.getElementById("tooltipPlaceholder"));
		} else {
			document.body.insertBefore(d, document.body.firstChild);
		}
		this.helpTip = d;
	},

	createHelpTip: function (el, sHtml) {
		if (this.helpTip == null) {
			this.create();
		}
		
		var d = this.helpTip;
		d.innerHTML = sHtml;
		d._boundAnchor = el;
		el._helpTip = d;
		return d;
	},

	// Allow clicks on A elements inside tooltip
	helpTipMouseDown: function (e) {
		var d = this;
		var el = d._boundAnchor;
		if (!e) e = event;
		var t = e.target || e.srcElement;
		while (t.tagName != "A" && t != d)
			t = t.parentNode;
		if (t == d) return;
		
		el._onblur = el.onblur;
		el.onblur = null;
	},

	helpTipMouseUp: function () {
		var d = this;
		var el = d._boundAnchor;
		el.onblur = el._onblur;
		el._onblur = null;
		el.focus();
	},

	anchorBlur: function (e) {
		var el = this;
		helpTipHandler.hideHelpTip(el);
	},

	anchorKeyDown: function (e) {
		if (!e) e = window.event
		if (e.keyCode == 27) { // ESC
			helpTipHandler.hideHelpTip(this);
		}
	},

	anchorMouseOut: function (e) {
		helpTipHandler.hideHelpTip(this);
	},

	removeHelpTip: function (d) {
		d._boundAnchor = null;
		d.style.filter = "none";
		d.innerHTML = "";
		d.onmousedown = null;
		d.onmouseup = null;
		d.parentNode.removeChild(d);
		//d.style.display = "none";
	},

	hideHelpTip: function (el) {
		var d = el._helpTip;
		/* Mozilla (1.2+) starts a selection session when moved
		and this destroys the mouse events until reloaded
		d.style.top = -el.offsetHeight - 100 + "px";
		*/
		
		d.style.visibility = "hidden";
		//d._boundAnchor = null;
		
		el.onblur = null;
		el._onblur = null;
		el._helpTip = null;
		el.onkeydown = null;
		
		this.showSelects(true);
	},

	positionToolTip: function (e) {
		this.showSelects(false);
		var scroll = this.getScroll();
		var d = this.helpTip;
		
		// width
		if (d.offsetWidth >= scroll.width)
			d.style.width = scroll.width - 10 + "px";
		else
			d.style.width = "";
		
		// left
		if (e.clientX > scroll.width - d.offsetWidth)
			d.style.left = scroll.width - d.offsetWidth + scroll.left + "px";
		else
			d.style.left = e.clientX - 2 + scroll.left + "px";
		
		// top
		if (e.clientY + d.offsetHeight + 18 < scroll.height)
			d.style.top = e.clientY + 18 + scroll.top + "px";
		else if (e.clientY - d.offsetHeight > 0)
			d.style.top = e.clientY + scroll.top - d.offsetHeight + "px";
		else
			d.style.top = scroll.top + 5 + "px";
		
		d.style.visibility = "visible";
	},

	// returns the scroll left and top for the browser viewport.
	getScroll: function () {
		if (document.all && typeof document.body.scrollTop != "undefined") {        // IE model
			var ieBox = document.compatMode != "CSS1Compat";
			var cont = ieBox ? document.body : document.documentElement;
			return {
				left:cont.scrollLeft,
				top:cont.scrollTop,
				width:cont.clientWidth,
				height:cont.clientHeight
			};
		} else {
			return {
				left:window.pageXOffset,
				top:window.pageYOffset,
				width:window.innerWidth,
				height:window.innerHeight
			};
		}
	}

};

function formatPrice(price) {
	if (isNaN(price)) {
		return Number.NaN;
	}
	var parts = (price + "").split(".");
	var result = "";
	var left = parts[0];
	var startGroupLength = left.length % 3;
	var fullPartsCount = (left.length - startGroupLength) / 3;
	result += left.substring(0, startGroupLength) + " ";
	for (var i = startGroupLength; i < fullPartsCount * 3; i += 3) {
		result += left.substring(i, i + 3);
		if (i + 3 < fullPartsCount * 3) {
			result += " ";
		}
	}
	if (parts.length == 2) {
		result += "," + parts[1].substring(0, 2);
	}
	return result;
}

function updateOrderForm(form, totalContainer) {
	var total = 0;
	for (var i in form.priceInputs) {
		var el = form.priceInputs[i];
		var v = el.value;
		if (!isNaN(v) && v > 0 && (Math.floor(v) == v)) {
			total += v * el.price;
			el.sumField.innerHTML = formatPrice(v * el.price);
		} else {
			el.sumField.innerHTML = "---";
		}
	}
	totalContainer.innerHTML = formatPrice(total);
}


var classNameRegexpCacheCommon = {};

function getRuntimeStyle(obj, propertyName) {
	 return obj.currentStyle ? obj.currentStyle[propertyName] : window.getComputedStyle(obj, null).getPropertyValue(propertyName);
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function placeMenu(elements) {
	var ul = elements.children('li');
		first = $('<li class="first"><ul></ul></li>'),
		last = $('<li class="last"><ul></ul></li>');

	elements.prepend(first,last);
	var first_ = first.children(),
		last_ = last.children();
	elements.css({
        display: "block",
        left: "-10000px"
    });
	for(var i = 0; i<ul.length; i++){
		if (first.outerHeight()<=last.outerHeight()){
            first_.append(ul.eq(i));
        } else {
            last_.append(ul.eq(i));
        }
    }
	elements.removeAttr("style");
}

Date.prototype.addDays = function(d) {
	  this.setDate( this.getDate() + d );
};
Date.prototype.getMoscowDate = function() {
	this.setHours( this.getUTCHours() + 4 );
	return this;
};

var DeliveryCalculate = function(settings) {
	this.locationSettings = settings.locationSettings;
    this.modelSettings = settings.modelSettings;
    this.resultSettings = settings.resultSettings;
    this.preloader = settings.preloader;
    this.countItem = 0;
    this.autoCalcByCity = true;
    this.serverUrl = this.locationSettings.input.attr("link");
    this.autocomlite = null; 
	
    
    this.month = ["января", "февраля", "марта", "апреля", "мая", "июня", "июля",
                  "августа", "сентября", "октября", "ноября", "декабря"];
 
    this.uiItem = {
		realValue: this.locationSettings.input.attr("realValue"),
		value: this.locationSettings.input.val()
	};

    this.locationModule();
    this.modelModule();
    this.resultModule();

    var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") >= 0, 
    	isiPhone = navigator.userAgent.indexOf('iPhone') >= 0; 
    
    if (!isAndroid && !isiPhone) {
    	this.modelSettings.select.selectBox();
    }

}

DeliveryCalculate.prototype.locationModule = function(){
	var btnChange = this.locationSettings.btnChange,
    hiddenInput = this.locationSettings.hiddenInput,
    input = this.locationSettings.input,
    text = this.locationSettings.text,
    textW = text.width(),
    noCity = hiddenInput.children("p"),
	cache = {},
	lastXhr,
    self = this,
    flagUiAutoomplite = false,
    response_ = [];
	
	input.keyup(function(e) {
		if(e.which == 13 && (!flagUiAutoomplite)) {
			if (input.val() == self.uiItem.value) {
				self.calculateResult();
				return;
			}
		}
		if (flagUiAutoomplite) flagUiAutoomplite = false;
		if ((e.which == 13) && (response_.length == 1)) {
			self.uiItem = response_[0];
			$('.delivery-small-block_link').eq(0).text(response_[0].value + " (изменить)");
			input.val(response_[0].value);
			self.closeInputField();
			self.calculateResult();
		}
		response = [];
	}).focusin(function(){
        input.autocomplete( "search" , input.val() );
    });
		
	btnChange.click(function() {
		self.openInputField();
	});
	
	this.autocomlite = input.autocomplete({
		minLength: 2,
		delay: 200,
		source: function( request, response ) {
			request.term = request.term.split(",")[0];
			var term = request.term;
			if ( term in cache ) {
				response( cache[ term ] );
				if (cache[term].length < 1) {
					noCity.show();
				} else {
					noCity.hide();
				}
				response_ = cache[ term ];
				return;
			}

			lastXhr = $.getJSON( self.serverUrl + "?action=GETCITY", request, function( data, status, xhr ) {
				cache[ term ] = data;
				if ( xhr === lastXhr ) {
					response( data );
				}
				if (data.length < 1) {
					noCity.show();
				} else {
					noCity.hide();
				}
				response_ = data;
				
			});
		},
		select: function( event, ui ) {
			flagUiAutoomplite = true;
			self.uiItem = ui.item;
			$('.delivery-small-block_link').eq(0).text(ui.item.value + " (изменить)");
			input.val(ui.item.value);
			/*$.cookie("deliveryCity",ui.item.value, {
				expires: d,
				path: "/"
			});*/
			/*$.cookie("deliveryCityrealval",ui.item.realValue, {
				expires: d,
				path: "/"
			});*/
			if (ui.item.value.toLowerCase().indexOf("москва") > -1) {
				$(".delivery-small-block h3").last().show();
			} else {
				$(".delivery-small-block h3").last().hide();
			}
			self.calculateResult();
		}
	});

}

DeliveryCalculate.prototype.openInputField = function() {
	var btnChange = this.locationSettings.btnChange,
		hiddenInput = this.locationSettings.hiddenInput,
	    input = this.locationSettings.input,
	    text = this.locationSettings.text,
	    textW = text.width(),
	    noCity = hiddenInput.children("p"),
	    self = this;
	
	if (hiddenInput.filter(':hidden').length > 0) {
    	noCity.hide();
    	self.resultSettings.result.hide();
        hiddenInput.css({width:"0px",overflow:"hidden"}).show().animate({width: '+=385px'},300, function(){
            hiddenInput.css({overflow:"visible"});
        });
        text.animate({width: '-=' + textW + 'px'},textW, function() {text.hide()});
        input[0].focus();
        btnChange.hide();
    }
}

DeliveryCalculate.prototype.closeInputField = function() {
	var btnChange = this.locationSettings.btnChange,
		hiddenInput = this.locationSettings.hiddenInput,
	    input = this.locationSettings.input,
	    text = this.locationSettings.text,
	    textW = text.width(),
	    noCity = hiddenInput.children("p"),
	    self = this;
	
	if (hiddenInput.filter(':visible').length > 0) {
        hiddenInput.css({width:"0px",overflow:"hidden"}).animate({width: '-=385px'},300, function(){
            hiddenInput.css({overflow:"visible",display:"none"}).hide();
        });
        text.animate({width: '+=' + textW + 'px'},textW,function(){text.width("auto")}).show();
        if (input.val() != "") {
            text.text(input.val());
        }
        btnChange.show();
        if (this.validate()) {
        	self.resultSettings.result.show();
        }
        self.autocomlite.autocomplete( "close" );
    }
}

DeliveryCalculate.prototype.getMinuteString = function(i) {
	if ((i > 10) && (i < 20)) {
		return i + " минут";
	}
	if ((i % 10 == 1)) {
		return i + " минута";
	} 
	if ((i % 10 > 1) && (i % 10 < 5)) {
		return i + " минуты";
	}
	return i + " минут";
}

DeliveryCalculate.prototype.getHourString = function(i) {
	if ((i > 10) && (i < 20)) {
		return i + " часов";
	}
	if ((i % 10 == 1)) {
		return i + " час";
	} 
	if ((i % 10 > 1) && (i % 10 < 5)) {
		return i + " часа";
	}
	return i + " часов";
}

DeliveryCalculate.prototype.changeDeliveryNote = function(json){
	var select = this.modelSettings.select.find(":selected"),
	    note = this.resultSettings.resultNote,
	    location = this.locationSettings.input.val().toLowerCase(),
	    self = this,
		currentDate = new Date().getMoscowDate(),
		var1 = "",
		var2 = "";
	
	var	forCapital = "Хотите получить товар в {var1}? Сделайте заказ в течение {var2}!",
		forOther = "Комплектация заказа {var1}. Ожидаемая дата передачи в службу доставки {var2}",
		constDays = ["воскресенье","понедельник","вторник","среду","четверг","пятницу","субботу"],
		notAvailable = "Дату доставки заказа уточняйте у продавца";
	
	
		if ((select.attr("count") != "0")) {
			 $.ajax({
		        data: {
		            city: self.uiItem.realValue,
		            action: "GETTIME"
		        },
		        dataType: "json",
		        url: self.serverUrl,
		    	type: "POST",
		        success: function(json){
		        	currentDate = new Date(json.date);
					if ((location.indexOf("москва") >= 0) || (location.indexOf("московская") >= 0)) {
						if ((currentDate.getDay() == 0) || (currentDate.getDay() == 6)) {
							currentDate.addDays(2 + currentDate.getDay()/6);
						} else {
							if ((currentDate.getHours() > 10) && (currentDate.getHours() < 18)) {
								var1 = constDays[currentDate.getDay()] + " " + currentDate.getDate() + " " + self.month[currentDate.getMonth()];
								var temp1 = "",temp2 = "";
								if (17 - currentDate.getHours() > 0) {
									temp1 = self.getHourString(17 - currentDate.getHours());
								}
								if (59 - currentDate.getMinutes() > 0) {
									temp2 = self.getMinuteString(59 - currentDate.getMinutes());
								}
								var2 = temp1 + " " + temp2;
								note.text(forCapital.replace("{var1}",var1).replace("{var2}",var2));
								return true;
							} else if (currentDate.getHours() <= 10) {
								
							} else {
								currentDate.addDays(1);
							} 
						}
					} else {
						if ((currentDate.getDay() == 0) || (currentDate.getDay() == 6)) {
							currentDate.addDays(2 + currentDate.getDay()/6);
						} else {
							if ((currentDate.getHours() < 11) || (currentDate.getHours() > 17)) {
								currentDate.addDays(1);
							}
						}
					}
					var1 = currentDate.getDate() + " " + self.month[currentDate.getMonth()];
					currentDate.addDays(1);
					var2 = currentDate.getDate() + " " + self.month[currentDate.getMonth()];
					note.text(forOther.replace("{var1}",var1).replace("{var2}",var2));
				
		        }
			 })
		} else {
			note.text(notAvailable);
		}
		
		if (json) {
			if ((json[0].weight < 3)) {
				$('.dc_result_note').show();
				$('.dc_result-table_header th:last').text("Оценочная стоимость доставки заказа весом 3 кг");
			} else {
				$('.dc_result_note').hide();
				var weight = json[0].weight.toFixed(3),
					weightD = weight.indexOf(".");
				
				for (var i = weight.length-1; i >= 0; i--) {
					if (((weight[i] == "0") || (weight[i] == "."))&& (weightD<=i) && (weightD != -1)) {
						weight = weight.substr(0,i);
					}
				}
				$('.dc_result-table_header th:last').text("Оценочная стоимость доставки заказа весом " + weight + " кг");
			}
		}
}


DeliveryCalculate.prototype.modelModule = function(){
    var select = this.modelSettings.select,
        text = this.modelSettings.text,
        self = this;
    
    select.find(":selected").removeAttr("selected");
    select.children().eq(0).attr("selected","yes");
    select.change(function(){
        self.changeDeliveryNote();
        self.correctDeliveryDate();
        select.focus();
    }).trigger("change");
    
    
}

DeliveryCalculate.prototype.correctDeliveryDate = function (attr) {
	var select = this.modelSettings.select,
	    text = this.modelSettings.text,
	    self = this,
		countItem = select.find(":selected").attr("count");
	
		if (!attr) {
			if (select.find(":selected").hasClass("not")) {
				
			} else {
				if (parseInt(countItem) > 0) {
					attr = "term";
				} else {
					//attr = "termDays";
				}
			}
		}
	
	this.resultSettings.resultTable.find("td[term]").each(function() {
		if (attr) {
			$(this).text($(this).attr(attr));
		} else {
			$(this).text("");
		}
	});
}

DeliveryCalculate.prototype.showPreloader = function() {
	var container = $("#delivery-calculate"),
		self = this;
	self.preloader.show();
	self.preloader.height(container.height());
}

DeliveryCalculate.prototype.getDeliveryCompany = function(){
    var self = this,
        result = "",
    	div = this.resultSettings.result,
    	table = this.resultSettings.resultTable,
    	data = {
                city: self.uiItem.realValue,
                article: self.modelSettings.select.find(":selected").attr("value"),
                quantity: self.modelSettings.count.val(),
                action: "GETCOMPANY"
            }
    
    	if (self.modelSettings.select.find(":selected").attr("weight")) {
    		data.weight = self.modelSettings.select.find(":selected").attr("weight");
    	}
    	
    	
    $.ajax({
        data: data,
        dataType: "json",
        url: self.serverUrl,
    	type: "POST",
    	beforeSend: function() {
    		self.showPreloader();
		},
		complete: function(json, textStatus){
			try {
				json = eval(json.responseText);
			} catch (e) {
				self.preloader.hide();
        		alert("Возникла ошибка, попробуйте воспользоваться сервисом позже.");
        		return;
			} 
        	if ((json.length > 0) && (textStatus == "success")) {
	        	var select = self.modelSettings.select.find(":selected"),
	        		p = "",
	        		fl = false;
	            for(var i = 0;  i<json.length; i++) {
	            	if (json[i].company.indexOf("Пункт выдачи, г. Москва, м. Павелецкая") > -1) {
	            		p = "<span style='color:red;'>*</span>";
	            		fl = true;
	            	} else {
	            		p = "";
	            	}
	                result += "<tr class='" + ((i%2 == 0) ? "even" : "odd" ) + "'>"
		                		+ "<td>" 
		                			+ json[i].company
		                			+ ((json[i].address == "") ? "" : " <br />(" + json[i].address.replace(/;/g,";<br>") + ")" ) 
	                			+ " " + p + " </td>"
		                		+ "<td term='" + json[i].term + "' termDays='" + json[i].termDays + "'>" 
		                		+ "</td>"
		            			+ "<td>" + (($.trim(json[i].cost) == "0") ? "бесплатно" : "от " + json[i].cost + " руб." ) + " (" + json[i].paymentType + ") " + p + "</td>"
	                		+ "</tr>";
	            }
	            table.find("tr").not(".dc_result-table_header").remove();
	        	table.append(result);
	        	self.preloader.hide();
        		div.show();
        		if (fl) {
        			$("#ds_for_pavalac").show();
        		} else {
        			$("#ds_for_pavalac").hide();
        		}
        		self.changeDeliveryNote(json);
        		self.correctDeliveryDate();
        	} else {
        		self.preloader.hide();
        		alert("Возникла ошибка, попробуйте воспользоваться сервисом позже.");
        	}
        }
    });
}

DeliveryCalculate.prototype.validate = function() {
	
	$("#no-article").remove();
	
	if (this.locationSettings.input.val() != this.uiItem.value) { 
		return false;
	}
	
	if (this.modelSettings.select.find(":selected").hasClass("not")) {
		this.modelSettings.select.after("<span id='no-article'>Вы должны выбрать артикул.</span>");
		return false;
	} 
	
	return true;
}

DeliveryCalculate.prototype.calculateResult = function() {
	var input = this.locationSettings.input,
    	text = this.locationSettings.text;

    this.closeInputField();
    if (!this.validate()) return;

    this.getDeliveryCompany();
}

DeliveryCalculate.prototype.resultModule = function() {
    var div = this.resultSettings.result,
        button = this.resultSettings.resultBtn,
        self = this;

    button.click(function(){
        self.calculateResult();
        return false;
    });
    
//    self.locationSettings.input.change(function() {
//    	if (self.autoCalcByCity) {
//    		self.calculateResult();
//    	}
//	})
}



DeliverySmallCalculate =  function(settings) {
	this.locationSettings = settings.locationSettings;
    this.resultSettings = settings.resultSettings;
    this.preloader = settings.preloader;
    this.countItem = 0;
    this.autoCalcByCity = true;
    this.serverUrl = this.locationSettings.input.attr("link");
    this.autocomlite = null; 
	
    
    this.uiItem = {
		realValue: this.locationSettings.input.attr("realValue"),
		value: this.locationSettings.input.val()
	};

    this.locationModule();
    if (this.resultSettings.result.length >= 1) { 
    	this.resultModule()
    }


}

DeliverySmallCalculate.prototype.locationModule = function(){
	var btnChange = this.locationSettings.btnChange,
    hiddenInput = this.locationSettings.hiddenInput,
    input = this.locationSettings.input,
    text = this.locationSettings.text,
    textW = text.width(),
    noCity = hiddenInput.children("p"),
	cache = {},
	lastXhr,
    self = this,
    flagUiAutoomplite = false,
    response_ = [];
	
	input.keyup(function(e) {
		if(e.which == 13 && (!flagUiAutoomplite)) {
			if (input.val() == self.uiItem.value) {
				self.calculateResult();
				return;
			}
		}
		if (flagUiAutoomplite) flagUiAutoomplite = false;
		if ((e.which == 13) && (response_.length == 1)) {
			self.uiItem = response_[0];
			$('.delivery-small-block_link').eq(0).text(response_[0].value + " (изменить)");
			input.val(response_[0].value);
			self.closeInputField();
			self.calculateResult();
		}
		response = [];
	}).focusin(function(){
        input.autocomplete( "search" , input.val() );
    });
		
	btnChange.click(function() {
		self.openInputField();
	});
	
	this.autocomlite = input.autocomplete({
		minLength: 2,
		delay: 200,
		source: function( request, response ) {
			request.term = request.term.split(",")[0];
			var term = request.term;
			if ( term in cache ) {
				response( cache[ term ] );
				if (cache[term].length < 1) {
					noCity.show();
				} else {
					noCity.hide();
				}
				response_ = cache[ term ];
				return;
			}

			lastXhr = $.getJSON( self.serverUrl + "?action=GETCITY", request, function( data, status, xhr ) {
				cache[ term ] = data;
				if ( xhr === lastXhr ) {
					response( data );
				}
				if (data.length < 1) {
					noCity.show();
				} else {
					noCity.hide();
				}
				response_ = data;
				
			});
		},
		select: function( event, ui ) {
			flagUiAutoomplite = true;
			self.uiItem = ui.item;
			$('.delivery-small-block_link').eq(0).text(ui.item.value + " (изменить)");
			input.val(ui.item.value);
			self.calculateResult();
		},
		open: function() {
			var au = input.autocomplete( "widget" );
			au.css({top: (input.offset().top + input.outerHeight())+"px",left: (input.offset().left-10)+"px"})
		},
        close: function(e, ui){
        }
	});
	
	

}

DeliverySmallCalculate.prototype.correctDeliveryDate = function (attr) {
	this.resultSettings.resultTable.find("td[term]").each(function() {
		$(this).text($(this).attr('termdays'));
	});
}

DeliverySmallCalculate.prototype.getDeliveryCompany = function(){
    var self = this,
        result = "",
    	div = this.resultSettings.result,
    	table = this.resultSettings.resultTable;
    	
    $.ajax({
        data: {
            city: self.uiItem.realValue,
            weight: self.resultSettings.weight.val(),
            action: "GETCOMPANYSHORT"
        },
        dataType: "json",
        url: self.serverUrl,
    	type: "POST",
    	beforeSend: function() {
    		self.showPreloader();
		},
		complete: function(json, textStatus){
			try {
				json = eval(json.responseText);
			} catch (e) {
				self.preloader.hide();
        		alert("Возникла ошибка, попробуйте воспользоваться сервисом позже.");
        		return;
			} 
        	if ((json.length > 0) && (textStatus == "success")) {
        		var p = "",
	        		fl = false;
	            for(var i = 0;  i<json.length; i++) {
	            	if (json[i].company.indexOf("Пункт выдачи, г. Москва, м. Павелецкая") > -1) {
	            		p = "<span style='color:red;'>*</span>";
	            		fl = true;
	            	} else {
	            		p = "";
	            	}
	            	if (json[i].company.indexOf("Pony Express") >= 0) {
	            		json[i].cost = parseFloat(json[i].cost) + 100; 
	            	}
	                result += "<tr class='" + ((i%2 == 0) ? "even" : "odd" ) + "'>"
		                		+ "<td>" 
		                			+ json[i].company
		                			+ ((json[i].address == "") ? "" : " <br />(" + json[i].address.replace(/;/g,";<br>") + ")" ) 
	                			+ " " + p + " </td>"
		                		+ "<td term='" + json[i].term + "' termDays='" + json[i].termDays + "'>" 
		                		+ "</td>"
		            			+ "<td>" + (($.trim(json[i].cost) == "0") ? "бесплатно" : "от " + json[i].cost + " руб." ) + " (" + json[i].paymentType + ") " + p + "</td>"
	                		+ "</tr>";
	            }
	            table.find("tr").not(".dc_result-table_header").remove();
	        	table.append(result);
	        	self.preloader.hide();
        		div.show();
        		self.correctDeliveryDate();
        	} else {
        		self.preloader.hide();
        		alert("Возникла ошибка, попробуйте воспользоваться сервисом позже.");
        	}
        }
    });
}


DeliverySmallCalculate.prototype.openInputField = function() {
	var btnChange = this.locationSettings.btnChange,
		hiddenInput = this.locationSettings.hiddenInput,
	    input = this.locationSettings.input,
	    text = this.locationSettings.text,
	    textW = text.width(),
	    noCity = hiddenInput.children("p"),
	    self = this;
	
	if (hiddenInput.filter(':hidden').length > 0) {
    	noCity.hide();
    	self.resultSettings.result.hide();
        hiddenInput.css({width:"0px",overflow:"hidden"}).show().animate({width: '+=385px'},300, function(){
            hiddenInput.css({overflow:"visible"});
        });
        text.animate({width: '-=' + textW + 'px'},textW, function() {text.hide()});
        input[0].focus();
        btnChange.hide();
    }
}

DeliverySmallCalculate.prototype.closeInputField = function() {
	var btnChange = this.locationSettings.btnChange,
		hiddenInput = this.locationSettings.hiddenInput,
	    input = this.locationSettings.input,
	    text = this.locationSettings.text,
	    textW = text.width(),
	    noCity = hiddenInput.children("p"),
	    self = this;
	
	if (hiddenInput.filter(':visible').length > 0) {
        hiddenInput.css({width:"0px",overflow:"hidden"}).animate({width: '-=385px'},300, function(){
            hiddenInput.css({overflow:"visible",display:"none"}).hide();
        });
        text.animate({width: '+=' + textW + 'px'},textW,function(){text.width("auto")}).show();
        if (input.val() != "") {
            text.text(input.val());
        }
        btnChange.show();
        if (this.validate()) {
        	self.resultSettings.result.show();
        }
        self.autocomlite.autocomplete( "close" );
    }
}

DeliverySmallCalculate.prototype.validate = function() {
	return true;
}

DeliverySmallCalculate.prototype.showPreloader = function() {
	var container = $("#delivery-calculate"),
		self = this;
	self.preloader.show();
	self.preloader.height(container.height());
}

DeliverySmallCalculate.prototype.calculateResult = function() {
	var input = this.locationSettings.input,
    	text = this.locationSettings.text;

    this.closeInputField();
    if (!this.validate()) return;

    this.getDeliveryCompany();
}

DeliverySmallCalculate.prototype.resultModule = function() {
    var div = this.resultSettings.result,
        button = this.resultSettings.resultBtn,
        self = this;

    button.click(function(){
        self.calculateResult();
        return false;
    });
    
//    self.locationSettings.input.change(function() {
//    	if (self.autoCalcByCity) {
//    		self.calculateResult();
//    	}
//	})

}

var ToolsOrders = function(settings) {
	this.orders = settings.orders;
	this.pageid = settings.pageid;
	this.fields = settings.fields;
	this.reset = settings.reset;
	
	this.binds();
}

ToolsOrders.prototype.update = function() {
	var values = {},
		self = this;
	
	for(var i=0; i<self.fields.length; i++) {
		values[self.fields[i]] = $("[name='" + self.fields[i] + "']").val();
	}
	self.orders.css({opacity:"0.3"});
	$.ajax({
		type: 'POST',
		url: "/system/modules/com.gridnine.opencms.modules.komfort/provider/tools-provider.jsp",
		data:values,
		success: function(data) {
			self.orders.html(data);
			self.orders.css({opacity:"1"});
		},
		error: function(data) {
			alert("Ошибка.");
			self.orders.css({opacity:"1"});
		} 
	})
}

ToolsOrders.prototype.resetForm = function() {
	var form = this.pageid.parents("form");
	
	form.find("[name='dateFrom']").val("");
	form.find("[name='dateTo']").val("");
	form.find("[name='pageNumber']").val("");
	form.find("[name='orderNumber']").val("");
	this.update();
}

ToolsOrders.prototype.binds = function() {
	var self = this;
		
	this.pageid.change(function() {
		self.update.call(self);
	});
	
	this.pageid.parents("form").submit(function() {
		self.update.call(self);
		return false;
	});
	
	this.reset.click(function() {
		self.resetForm.call(self);
	})
}

var updateSkypeStatus = function() {
	$.ajax({
	  type: 'POST',
	  async: true,
	  url: '/system/modules/com.gridnine.opencms.modules.komfort/provider/skype-detector',
	  data: {},
	  success: function(data) {
			if (data.status) {
				$(".skype-button").show();
			} else {
				$(".skype-button").hide();
			}
	 },
	  dataType: "JSON"
	});
}


$(function() {

	window.onerror = function (msg, url, line) {

	    var logUrl = "/common/json/jsErrorLog.html",
	        str = "\nMessage: " + msg +
	              "\nScript: " + url +
	              "\nURL: " + window.location.href +
	              "\nLine:" + line;
	
	    $.post(logUrl, {log: str}, function(){}, "text");
	
	    return true;
	
	};
	

	$('.submenu').each(function() {
		placeMenu($(this));
	});
	
	$('.menu>ul>li').hover(function(e) {
		var submenu = $(this).children('.submenu');
		submenu.show();
		var h = submenu.outerHeight(),
			wh = $(window).height(),
			topScroll = $(window).scrollTop(),
			top = $(this).offset().top,
			fromTop = top-topScroll;
		
		if(fromTop+h>wh) {
			var margin = wh-fromTop-h;
			if (Math.abs(margin)>fromTop) {
				margin = -fromTop;
			}
			submenu.css("margin-top",margin+"px");
		} else {
			submenu.css("margin-top", "-10px");
		}
		
	}, function() {
		$(this).children('.submenu').hide();
	});
	
	var deliveryCalculatePopup = $(".delivery-small-block_link").overlay({
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.7
		},
		target: "#delivery-calculate",
		onLoad: function () {
			$('body').scrollTop($("#delivery-calculate").scrollTop());
		}
	});
	
	if ($("#delivery-calculate").length > 0) {
		var deliveryCalculate = new DeliveryCalculate({
		    locationSettings: {
		        btnChange: $("#delivery-calculate .dc_region-change"),
		        hiddenInput: $("#delivery-calculate .dc_region-input"),
		        text: $("#delivery-calculate .dc_region span"),
		        input: $('#delivery-calculate #dc_region-input')
		    },
		    modelSettings: {
		        select: $("#delivery-calculate #dc_choose-model"),
		        text: $("#delivery-calculate .dc_in-stock"),
		        count: $("#delivery-calculate #dc_choose-col")
		    },
		    resultSettings: {
		        result: $('#delivery-calculate .dc_result'),
		        resultTable: $('#delivery-calculate .dc_result-table'),
		        resultBtn: $('#delivery-calculate .dc_calsulate-btn'),
		        resultNote: $('#delivery-calculate #dc_result_note')
		    },
		    preloader: $("#delivery-calculate #dc_preloader")
		});
	}
	
	$(".delivery-calculate_open").overlay({
		top: 50,
		mask: {
			color: '#000',
			loadSpeed: 200,
			opacity: 0.7
		},
		target: "#popup-window",
		onLoad: function() {
			$(window).scrollTop(0);
		}

	});
	var temp = $("#delivery-block .to-popup")
	$('#popup-window_body').html(temp.html());
	temp.remove();
	$('#popup-window_title').html("Оценка стоимости и срока доставки");
	if ($('#popup-window').length > 0) {
		$('#popup-window').data('DeliverySmallCalculate', new DeliverySmallCalculate({
		    locationSettings: {
		        btnChange: $("#popup-window .dc_region-change"),
		        hiddenInput: $("#popup-window .dc_region-input"),
		        text: $("#popup-window .dc_region span"),
		        input: $('#popup-window #dc_region-input')
		    },
		    resultSettings: {
		        result: $('#popup-window .dc_result'),
		        resultTable: $('#popup-window .dc_result-table'),
		        resultBtn: $('#popup-window .dc_calsulate-btn'),
		        resultNote: $('#dc_result_note'),
		        weight: $('#dc_choose-col')
		    },
		    preloader: $("#dc_preloader")
		}));
	}
	
	/*var deliverySmallCalculate = new DeliverySmallCalculate({
	    locationSettings: {
	        btnChange: $("#delivery-block .dc_region-change"),
	        hiddenInput: $("#delivery-block .dc_region-input"),
	        text: $("#delivery-block .dc_region span"),
	        input: $('#delivery-block #dc_region-input')
	    },
	    resultSettings: {
	        result: $(''),
	        resultTable: $(''),
	        resultBtn: $(''),
	        resultNote: $(''),
	        weight: $('')
	    },
	    preloader: $("")
	});*/
	
	$(".search-tab").eq(0).addClass("active");
	$(".search-tab_result").eq(0).show();
	$(".search-tab").click(function() {
		$(".search-tab").removeClass("active");
		$(this).addClass("active");
		$(".search-tab_result").hide();
		$(".search-tab_result").eq($(".search-tab").index($(this))).show();
	});
	
	$(".zoomProduct").colorbox();
	
	var toolsOrders = new ToolsOrders({
		orders: $(".tools-orders"),
		pageid: $("#pageNumber"),
		fields: ["dateFrom","dateTo","orderNumber","pageNumber","pageLimit"],
		reset: $("#reset_filters")
	});
	
	
	
	//window.setInterval(updateSkypeStatus, 300000); // 5 minutes
	//updateSkypeStatus();
})
