//------------------------------------------------------------------------------------------------------------------------------------
//-- для диалог бокса с модификаторами
function nop (i,k) {return true;}
function showVariator (dialog,nop) {
	$.blockUI({ message: $(dialog), css: {top:($(window).height()-450)/2 + 'px', left:($(window).width()-520)/2 + 'px', width:'520px;'} });
	$('div.blockOverlay').bind('click',hideVariator);
	$(document).keyup(function(event) { if (event.keyCode == 27) {hideVariator()}});
	return false;
}
function hideVariator () {$.unblockUI(); return false;}
//--
var namePurchased = 'Purchased';
var nameComment = 'Comment';
var arSep = ',';
var elSep = ':';
var purchased = new Array();
var totalPrice=0;

$(document).ready(function(){
	$('.search input[name=query]').attr('placeholder', 'Поиск по сайту');
	
	$('.compare-add').live('click', function() {
		var pid = $('.compare-prods-opt').attr('pid');
		var article = $('.compare-prods-opt').attr('art');

		var pids = $.cookie('pids');
		var articles = $.cookie('articles');
		if (pids && pids.length > 0) {
			var pids_array = pids.split(',');
			var articles_array = articles.split(';');
		} else {
			pids_array = new Array();
			articles_array = new Array();
		}
		
		var inarray = false;
		for (var i = 0; i < pids_array.length; i++) {
			if (pid == pids_array[i]) inarray = true;
		}
		
		if (!inarray) {
			pids_array.push(pid);
			articles_array.push(article);
		}
		
		$('.compare-prods-opt').show();
		$.cookie('pids', pids_array.join(','), { path: '/', domain: 'sims2.ru' });
		$.cookie('articles', articles_array.join(';'), { path: '/', domain: 'sims2.ru' });
		updateCard();
		return false;
	});
	
	function updateCard() {
		var pids = $.cookie('pids');
		var articles = $.cookie('articles');
		
		var pids_array = pids.split(',');
		var articles_array = articles.split(';');
		
		if (pids && pids.length != 0) {
			var html = '<table>';
			for (var i = 0; i < pids_array.length; i++) {
				html += '<tr><td class="prods-name"><a href="?m=25&pid='+ pids_array[i] + '" class="atr-name">' + articles_array[i] + '</a></td><td><a href="#'+ pids_array[i] + '" class="remove-pid">&times;</a></td></tr>';
			}
			html += '<tr><td colspan="2" align="center" class="prods-compare"><a href="compare.php?pids='+ pids +'" target="_blank">Сравнить</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="clear-all">Очистить</a></td><td style="border: none"></td></tr></table>';
		} else {
			var html = '';
		}
		$('.update-table').html(html);
	};
	
	$('.remove-pid').live('click', function() {
		var pids = $.cookie('pids');
		var articles = $.cookie('articles');
		
		var pids_array = pids.split(',');
		var articles_array = articles.split(';');
		var thisPid = $('.remove-pid').attr('href').substr(1);
		
		for (var i = 0; i < pids_array.length; i++) {
			if (thisPid == pids_array[i]) {
				pids_array.splice(i, 1);
				articles_array.splice(i, 1);
			}
		}
		
		$.cookie('pids', pids_array.join(','), { path: '/', domain: 'sims2.ru' });
		$.cookie('articles', articles_array.join(';'), { path: '/', domain: 'sims2.ru' });
		updateCard();
		return false;
	});
	
	$('.compare-prods-add').live('click', function() {
		$('.compare-prods-opt').hide();
		$(this).parents('.compare-prods').find('.compare-prods-opt').show();
		
		var pid = $(this).parents('.compare-prods').find('.compare-prods-opt').attr('pid');
		var article = $(this).parents('.compare-prods').find('.compare-prods-opt').attr('art');

		var pids = $.cookie('pids');
		var articles = $.cookie('articles');
		if (pids && pids.length > 0) {
			var pids_array = pids.split(',');
			var articles_array = articles.split(';');
		} else {
			pids_array = new Array();
			articles_array = new Array();
		}
		
		var inarray = false;
		for (var i = 0; i < pids_array.length; i++) {
			if (pid == pids_array[i]) inarray = true;
		}
		
		if (!inarray) {
			pids_array.push(pid);
			articles_array.push(article);
		}
		
		$.cookie('pids', pids_array.join(','), { path: '/', domain: 'sims2.ru' });
		$.cookie('articles', articles_array.join(';'), { path: '/', domain: 'sims2.ru' });
		updateCard();
		return false;
	});
	
	$('.print a').click(function() {
		$('.print-options').show();
		return false;
	});
	
	$('.print-close').click(function() {
		$('.print-options').hide();
		return false;
	});

	$('.clear-all').live('click', function() {
		$.cookie('pids', null, { path: '/', domain: 'sims2.ru' });
		$.cookie('articles', null, { path: '/', domain: 'sims2.ru' });

		$('.compare-prods-opt').hide();
		return false;
	});

	cartInit();
	updateTotal();
	$("a#printorder").click(function() {$("div#printorderarea").printArea({mode: "popup", popClose: false});});
	
	$('.prods-close').click(function() {
		$('.compare-prods-opt').hide();
		return false;
	});
	
	$('.clear-list').live('click', function() {
		$.cookie('pids', null, { path: '/', domain: 'sims2.ru' });
		$.cookie('articles', null, { path: '/', domain: 'sims2.ru' });
	});
	
	$('.compare-delete').live('click', function() {
		var pid = $(this).attr('pid');
		var pids = $.cookie('pids');
		var articles = $.cookie('articles');
		
		var pids_array = pids.split(',');
		var articles_array = articles.split(';');
		for (var i=0; i<pids_array.length; i++) {
			if (pid == pids_array[i]) {
				pids_array.splice(i, 1);
				articles_array.splice(i, 1);
			}
		}
		$.cookie('pids', pids_array.join(','), { path: '/', domain: 'sims2.ru' });
		$.cookie('articles', articles_array.join(';'), { path: '/', domain: 'sims2.ru' });
		window.location.href='compare.php?pids=' + pids_array;
		return false;
	});
	
});
function setComment()
{
	var oc = document.getElementById('ocomment').value;
	$.cookie(nameComment, oc ? Base64.encode(oc) : null);
}

function cartPush(value)
{
	$.cookie(namePurchased, value ? Base64.encode(value) : null, {path:'/'});
}

function cartGet()
{
	var p = Base64.decode($.cookie(namePurchased));
	if (p.length) {purchased = p.split(arSep);}
}

function cartClear()
{
	cartPush(null);
	cartInit();
	updateTotal('Список заказов очищен');
}

function checkVariations(pid) {
	var elements = document.getElementsByName('mod_choose_' + pid + '[]');
	if (typeof (elements) != 'undefined' && elements.length) {
		var mods = new Array();
		for (var i = 0; i < elements.length; i++) {
			if (elements[i].checked) { //$('input[name=foo]').attr('checked', false);
				elements[i].checked = false;
				mods.push(Array(elements[i].value,elements[i].title));
			}
		}
	}
	return mods;
}

function cartInit()
{
	purchased = new Array();
	totalPrice=0;
	cartGet();
}

function cartAdd(product, title)
{
	if (typeof(product) == 'undefined') {product = 0;}
	if (typeof(title)   == 'undefined') {title = '';}
	
	product = parseInt(product,10);
	if (! product) {return false;}
	
	var variations = checkVariations(product);
	if (typeof(variations) == 'undefined') {
		if (cartCheck(product,0)) {
			purchased.push(product + elSep + '0' + elSep + '1' + elSep + '1');
			cartPush(purchased.join(arSep));
			updateTotal('Товар ' + title + ' добавлен в список заказов');
		} else {
			updateTotal('Товар ' + title + ' уже в списке заказов');
		}
	}
	else if (variations.length) {
		var exists = false;
	    $.each(variations, function() {
	    	var mod = this;
			if (cartCheck(product,mod[0])) {
				purchased.push(product + elSep + mod[0] + elSep + '1' + elSep + '1');
				updateTotal('Товар ' + title + ' (' + mod[1] + ')  добавлен в список заказов');
			} else {
				updateTotal('Товар ' + title + ' (' + mod[1] + ') уже в списке заказов');
			}
		});
		cartPush(purchased.join(arSep));
	}
	else if (variations.length == 0){
		updateTotal('Укажите вариацию товара ' + title);
	}
	//alert(purchased);
	cartInit();
	return false;
}

function cartCheck(pid,mid)
{
	var out = true;
	if (typeof(pid)=='undefined' || pid < 0) {pid=0;}
	if (typeof(mid)=='undefined' || mid < 0) {mid=0;}
	$.each(purchased, function() {
		// получаем элемент корзины (0: продукт ID, 1: модификация товара, 2: кол-во в заказ, 3: цена за единицу товара)
		var element = this.split(elSep);
		var p = parseInt('0' + element[0], 10);
		var m = parseInt('0' + element[1], 10);
		if (p == pid && m == mid) {
			out = false;
		}
	});
	return out;
}

function cartRemove(product,mod)
{
	var purnew = new Array();
    $.each(purchased, function() {
		var element = this.split(elSep);
		var pid = parseInt('0' + element[0], 10);
		var mid = parseInt('0' + element[1], 10);
		if(pid != product || mid != mod) {
			purnew.push(this);
		}
	});
	$('tr.productID' + product + 'modifierID' + mod).remove();
	cartPush(purnew.join(arSep));
	cartInit();
	updateTotal('Товар ' + '' + ' удален');
}

function updateTotal(msg)
{
	if(purchased.length > 0) {
		$('span#totalCount').html('('+purchased.length+') <a href="#" onclick="cartClear();return false;" title="Очистить корзину товаров"><img src="img/clear1.gif" onmouseover="this.src=\'img/clear2.gif\'" onmouseout="this.src=\'img/clear1.gif\'" /></a>');
		$('table.pubCartList').show();
		$('div.pubCartMsgClear').hide();
	} else {
		$('span#totalCount').html('');
		$('table.pubCartList').hide();
		$('div.pubCartMsgClear').show();
	}

	if ($('table').hasClass('pubCartList'))
	{
		totalPrice = 0;
		$.each(purchased, function() {
			var p = this.split(elSep);
			$('input#productCount' + parseInt(p[0],10) + 'mID' + parseInt(p[1],10)).val(parseInt(p[2],10));
			$('input#productPrice' + parseInt(p[0],10) + 'mID' + parseInt(p[1],10)).val(parseInt(p[3],10));
			totalPrice += parseInt(p[2],10)*parseInt(p[3],10);
	    });
		$('span#totalPrice').html(totalPrice);
    }
    if (msg) {
    	$.notif(msg);
    }
}
$(document).ready(function(){
	$('tr .tdnav:nth-child(1)').css('border-left', '1px solid #E5E5E5');
});

function cartCalculate()
{
    $.each(purchased, function(i) {
		var p = this.split(elSep);
		var newCount = '0' + $('input#productCount' + p[0] + 'mID' + p[1]).val();
		var newPrice = '0' + $('input#productPrice' + p[0] + 'mID' + p[1]).val();
		var tmp = parseInt(newCount,10) * parseInt(newPrice,10);
		purchased[i] = p[0] + elSep + p[1] + elSep + parseInt(newCount,10) + elSep + parseInt(newPrice,10);
		//alert('new: '+purchased[i]);
    });
	cartPush(purchased.join(arSep));
	cartInit();
	updateTotal('Сумма заказа пересчитана');
}


//------------------------------------------------------------------------------------------------
// Конвертирование в Base64 и обратно  http://www.webtoolkit.info/
var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		if (input) {
			input = Base64._utf8_encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output +
				this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
				this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
			}
		}
		return output;
	},
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		if (input) {
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
			while (i < input.length) {
				enc1 = this._keyStr.indexOf(input.charAt(i++));
				enc2 = this._keyStr.indexOf(input.charAt(i++));
				enc3 = this._keyStr.indexOf(input.charAt(i++));
				enc4 = this._keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = Base64._utf8_decode(output);
		}
		return output;
	},
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {utftext += String.fromCharCode(c);}
			else if((c > 127) && (c < 2048)) {utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); }
			else {utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128);}
		}
		return utftext;
	},
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {string += String.fromCharCode(c); i++;}
			else if((c > 191) && (c < 224)) {c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2;}
			else {c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3;}
		}return string;
	}
}



