/* Common Javascript functions for use throughout Interspire Shopping Cart */



// Fetch the value of a cookie

function get_cookie(name) {

	name = name += "=";

	var cookie_start = document.cookie.indexOf(name);

	if(cookie_start > -1) {

		cookie_start = cookie_start+name.length;

		cookie_end = document.cookie.indexOf(';', cookie_start);

		if(cookie_end == -1) {

			cookie_end = document.cookie.length;

		}

		return unescape(document.cookie.substring(cookie_start, cookie_end));

	}

}



// Set a cookie

function set_cookie(name, value, expires)

{

	if(!expires) {

		expires = "; expires=Wed, 1 Jan 2020 00:00:00 GMT;"

	} else {

		expire = new Date();

		expire.setTime(expire.getTime()+(expires*1000));

		expires = "; expires="+expire.toGMTString();

	}

	document.cookie = name+"="+escape(value)+expires;

}



/* Javascript functions for the products page */

var num_products_to_compare = 0;

var product_option_value = "";



function showProductImage(filename, product_id) {

	var l = (screen.availWidth/2)-350;

	var t = (screen.availHeight/2)-300;

	var variationAdd = '';

	if($('body').attr('currentVariation') != '' && typeof($('body').attr('currentVariation')) != "undefined") {

		variationAdd = '&variation_id='+$('body').attr('currentVariation');

	}

	window.open(filename + "?product_id="+product_id+variationAdd, "imagePop", "toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=700,height=600,top="+t+",left="+l);

}



function CheckProductConfigurableFields(form)

{

	var requiredFields = $('.FieldRequired');

	var valid = true;

	requiredFields.each(function() {

		var namePart = this.name.replace(/^.*\[/, '');

		var fieldId = namePart.replace(/\].*$/, '');

		

		if(this.type=='checkbox' ) {

			if(!this.checked) {

				valid = false;

				alert(lang.EnterRequiredField);

				this.focus();

				this.select();

				return false;

			}

		} else if(this.value == '') {

			if(this.type != 'file' || (this.type == 'file' && document.getElementById('CurrentProductFile_'+fieldId).value == '')) {

				valid = false;

				alert(lang.EnterRequiredField);

				this.focus();

				this.select();

				return false;

			}

		}

	});



	var fileFields = $(form).find('input[type=file]');

	fileFields.each(function() {

		if(this.value != '') {

			var namePart = this.name.replace(/^.*\[/, '');

			var fieldId = namePart.replace(/\].*$/, '');

			var fileTypes = document.getElementById('ProductFileType_'+fieldId).value;



			fileTypes = ','+fileTypes.replace(' ', '').toLowerCase()+','

			var ext = this.value.replace(/^.*\./, '').toLowerCase();



			if(fileTypes.indexOf(','+ext+',') == -1) {

				alert(lang.InvalidFileTypeJS);

				this.focus();

				this.select();

				valid = false;

			}



		}

	});



	return valid;

}



function check_add_to_cart(form, required) {

	var valid = true;

	var qtyInputs = $(form).find('input.qtyInput');

	qtyInputs.each(function() {

		if(isNaN($(this).val()) || $(this).val() <= 0) {

			alert(lang.InvalidQuantity);

			this.focus();

			this.select();

			valid = false;

			return false;

		}

	});

	if(valid == false) {

		return false;

	}



	if(!CheckProductConfigurableFields(form)) {

		return false;

	}



	if(required && !$(form).find('.CartVariationId').val()) {

		alert(lang.OptionMessage);

		var select = $(form).find('select').get(0);

		if(select) {

			select.focus();

		}

		var radio = $(form).find('input[type=radio]').get(0);

		if(radio) {

			radio.focus();

		}

		return false;

	}



	return true;

}



function compareProducts(compare_path) {

	var pids = "";

	

	if($('form').find('input[name=compare_product_ids][checked]').size() >= 2) {

		var cpids = document.getElementsByName('compare_product_ids');



		for(i = 0; i < cpids.length; i++) {

			if(cpids[i].checked)

				pids = pids + cpids[i].value + "/";

		}



		pids = pids.replace(/\/$/, "");

		document.location.href = compare_path + pids;
		return false;

	}

	else {

		alert(lang.CompareSelectMessage);

		return false;

	}

}



function product_comparison_box_changed(state) {

	// Increment num_products_to_compare - needs to be > 0 to submit the product comparison form

	

	

	if(state)

		num_products_to_compare++;

	else

		if (num_products_to_compare != 0)

			num_products_to_compare--;

}



function remove_product_from_comparison(id) {

	if(num_compare_items > 2) {

		for(i = 1; i < 11; i++) {

			document.getElementById("compare_"+i+"_"+id).style.display = "none";

		}



		num_compare_items--;

	}

	else {

		alert(lang.CompareTwoProducts);

	}

}



function show_product_review_form() {

	document.getElementById("rating_box").style.display = "";

	document.location.href = "#write_review";

}



function jump_to_product_reviews() {

	document.location.href = "#reviews";

}



function g(id) {

	return document.getElementById(id);

}



function check_product_review_form() {

	var revrating = g("revrating");

	var revtitle = g("revtitle");

	var revtext = g("revtext");

	var revfromname = g("revfromname");

	var captcha = g("captcha");



	/*if(revrating.selectedIndex == 0) {

		alert(lang.ReviewNoRating);

		revrating.focus();

		return false;

	}



	if(revtitle.value == "") {

		alert(lang.ReviewNoTitle);

		revtitle.focus();

		return false;

	}



	if(revtext.value == "") {

		alert(lang.ReviewNoText);

		revtext.focus();

		return false;

	}



	if(captcha.value == "" && HideReviewCaptcha != "none") {

		alert(lang.ReviewNoCaptcha);

		captcha.focus();

		return false;

	}*/



	return true;

}



function show_product_request(id)

{

	$('#li'+id).toggleClass('one_position_sel');

	$('#request_box'+id).toggle();

	$('#leave_req'+id).toggle(); $('#hide_req'+id).toggle();

	

}



function check_product_request(id)

{	

	var str = "revtitle"+id;	

	var revtitle = g(str);	

	var str = "captcha"+id;

	var captcha = g(str);	

	if(revtitle.value == "") {

		alert(lang.ReqNoMail);

		revtitle.focus();

		return false;

	}

	if(captcha.value == "") {

		alert(lang.ReqNoCaptcha);

		captcha.focus();

		return false;

	}



	return true;

}



function open_product_request(code, id)

{

	if (code)

	{

		show_product_request(id);

	}

}



function check_small_search_form() {

	var search_query = g("search_query");



	if(search_query.value == "") {

		alert(lang.EmptySmallSearch);

		search_query.focus();

		return false;

	}



	return true;

}



function setCurrency(currencyId)

{

	var gotoURL = location.href;



	if (location.search !== '')

	{

		if (gotoURL.search(/[&|\?]setCurrencyId=[0-9]+/) > -1)

			gotoURL = gotoURL.replace(/([&|\?]setCurrencyId=)[0-9]+/, '$1' + currencyId);

		else

			gotoURL = gotoURL + '&setCurrencyId=' + currencyId;

	}

	else

		gotoURL = gotoURL + '?setCurrencyId=' + currencyId;



	location.href = gotoURL;

}





// Dummy sel_panel function for when design mode isn't enabled

function sel_panel(id) {}



function inline_add_to_cart(filename, product_id, quantity, returnTo) {

	if(typeof(quantity) == 'undefined') {

		var quantity = '1';

	}

	var html = '<form action="' + filename + '/cart.php" method="post" id="inlineCartAdd">';

	if(typeof(returnTo) != 'undefined' && returnTo == true) {

		var returnLocation = window.location;

		html += '<input type="hidden" name="returnUrl" value="'+escape(returnLocation)+'" />';		

	}

	html += '<input type="hidden" name="action" value="add" />';

	html += '<input type="hidden" name="qty" value="'+quantity+'" />';

	html += '<input type="hidden" name="product_id" value="'+product_id+'" />';

	html += '<\/form>';

   $('body').append(html);

   $('#inlineCartAdd').submit();

}



// Dummy JS object to hold language strings.

var lang = {

};



function AddToCart(prodid, qty, msgbox){

	if(!qty) qty=1;



	if(!msgbox) msgbox = 'addtc' + prodid;

	if(!document.getElementById(msgbox)){

		$('#li'+prodid).append('<div id="' + msgbox + '" class="ProdAddedToCart"></div>');

	}

	$('#' + msgbox).show();

	$('#' + msgbox).html(lang.WaitPlease);

	

	setTimeout(function() { $('#' + msgbox).fadeOut('slow'); }, 7000);



	$.ajax({

		url: '/remote.php',

		type: 'GET',

		data: {

				'w': 'addtocart',

				'product_id': prodid,

				'qty': qty

		},

		dataType: 'json',

		success: function(obj)

		{

			if(obj.status && obj.status == 'ok'){

				$('#' + msgbox).html(lang.ProductAddedToCart);

				if(obj.cartitems){

					$('#TopMenuCartItems').html(obj.cartitems);

					$('#SideCartContentsText').html(obj.cartitems);

					$('#TopMenuCartItems').show();

					if(obj.countwls > 0) $('#SideWishlistBorder').show();

				}

				$('#SideCartContents').fadeIn('slow');

				var a = document.URL.split("//");
				a = (a[1] ? a[1] : a[0]).split("/");
				var url='/';
				var source='';
				if(a.length>1){
					a = a.splice(1,a.length-1);
					url += a.join("/");
					source = a[0];
				} else {
					source = 'index';
				}

				pageTracker._trackEvent('AddToCart_'+source, url, obj.prodname);



			} else if(obj.status){

				$('#' + msgbox).html(obj.status);

			} else {

				alert(lang.ProductAddingToCartFailed + ' ' + lang.TryAgainOrAskForHelp);

			}

			

		},

		error: function(obj)

		{

			error = lang.AddingToCartFailed + ' ' + lang.TryAgainOrAskForHelp;

			alert(error);

		}

	});	

	return false;

}



function AddToWishList(prodid){

	$('#wlstatus' + prodid).html(lang.WaitPlease);

	$.ajax({

		url: '/remote.php',

		type: 'GET',

		data: {

				'w': 'addtowishlist',

				'product_id': prodid,

				'wishlistid': $("input[@name='wishlistid"+prodid+"']:checked").val(),

				'wlcount': $('#wlcount'+prodid).val()

		},

		dataType: 'json',

		success: function(obj)

		{

			$('#li'+prodid).css('height', '');

			if(obj.err){

				$('#wlstatus' + prodid).removeClass();

				$('#wlstatus' + prodid).html(obj.err);			

				$('#wlstatus' + prodid).addClass('msgboxError');

			} else if(obj.suc){

				$('#wls' + prodid).slideUp('slow');

				$('#wlstatus' + prodid).html(obj.suc);

				$('#wlstatus' + prodid).addClass('favouriteOk');

				if(!obj.newwl || obj.newwl!=true){

					$('#wlstatus' + prodid).append('&nbsp;&nbsp;&nbsp;<b><a href="#" onclick="ShowWishLists('+prodid+'); return false" >' + lang.Else + '</a></b>');

				}

				if(obj.count){

					wlsItemsCount = wlsItemsCount + obj.count;

					$('.wlsItemsCount').html('('+wlsItemsCount +')');
                                        $('.wlsItemsCount').css("display","inline");

                                         if(obj.firstwlsname){
                                                $('.ViewWishlistLink').attr("href","/wishlist.php?action=viewwishlistitems&wishlistid="+obj.wishlistid)
                                                 $('.ViewWishlistLink').prepend(obj.firstwlsname)
                                                 $('.ViewWishlistLink b').attr("id","wishlist"+obj.wishlistid)
                                         }
                                        $('#wishlist'+obj.wishlistid).html('('+obj.sidecount +')');
                                                if(obj.itemsincart > 0) $('#SideWishlistBorder').show();
				}
                                $('#SideWishlistContents').fadeIn('slow');

			} else if(obj.notloggedin){

				$('#wlstatus' + prodid).addClass('msgboxInfo');

				$('#wlstatus' + prodid).html(lang.FirstlyCreateAnAccount);

			}

			

		},

		error: function(obj)

		{

			$('#li'+prodid).css('height', '');

			error = lang.AddingToWishListFailed + ' ' + lang.TryAgainOrAskForHelp;

			alert(error);

		}


	});	

	return false;

}



function ShowWishLists(prodid){

        $('#wls' + prodid).css('float','left');
	$('#wls' + prodid).slideDown('slow');

	$('#li'+prodid).css('height','');

}



function AddToCompare(prodid){

	$('#clstatus' + prodid).show();

	$('#clstatus' + prodid).html(lang.WaitPlease);

	$.ajax({

		url: '/remote.php',

		type: 'GET',

		data: {

				'w': 'addtocompare',

				'product_id': prodid

		},

		dataType: 'json',

		success: function(obj)

		{

			$('#li'+prodid).css('height', '');

			if(obj.status && obj.status =='ok'){

				$('#clstatus' + prodid).html(lang.ProductAddedToCompare);

				$('#clstatus' + prodid).append('<div style="text-align: center; padding-top: 3px;"><a href="#" onclick="DeleteFromCompare('+prodid+'); return false;">' + lang.DeleteFromCompare + '</a></div>');

				$('#clstatus' + prodid).addClass('msgboxSuccess');

			} else {

				$('#wlstatus' + prodid).html(lang.ProductAddingToCompareFailed);

				$('#wlstatus' + prodid).addClass('msgboxError');

			}		

		},



		error: function(obj)

		{

			$('#li'+prodid).css('height', '');

			error = lang.AddingToCompareFailed + ' ' + lang.TryAgainOrAskForHelp;

			alert(error);

		}

	});	

	return false;

}



function DeleteFromCompare(prodid){

	$('#clstatus' + prodid).show();

	$('#clstatus' + prodid).html(lang.WaitPlease);

	$.ajax({

		url: '/remote.php',

		type: 'GET',

		data: {

				'w': 'deletefromcompare',

				'product_id': prodid

		},

		dataType: 'json',

		success: function(obj)

		{

			if(obj.status && obj.status =='ok'){ 

				$('#clstatus' + prodid).html('<a href="#" onclick="AddToCompare(' + prodid + '); return false;">' + lang.AddToCompare + '</a>');

				$('#clstatus' + prodid).removeClass('msgboxSuccess');

			} else if(obj.status && obj.status == 'nosuchitem'){

				alert('No such item in your comparison list');

			} else {

				$('#clstatus' + prodid).html(lang.ProductDeletingFromCompareFailed);

				$('#clstatus' + prodid).addClass('msgboxError');

			}		



		

		},

		error: function(obj)

		{

			error = lang.DeletingFromCompareFailed + ' ' + lang.TryAgainOrAskForHelp;

			alert(error);

		}

	});	

	return false;

}

// IE 6 doesn't support the :hover selector on elements other than links, so

// we use jQuery to work some magic to get our hover styles applied.

if(document.all) {

	var isIE7 = /*@cc_on@if(@_jscript_version>=5.7)!@end@*/false;

	if(isIE7 == false) {

		$(document).ready(function() {

			/*$('.ProductList li').hover(function() {

				$(this).addClass('Over');

			},

			function() {

				$(this).removeClass('Over');

			});*/

			$('.ComparisonTable tr').hover(function() {

				$(this).addClass('Over');

			},

			function() {

				$(this).removeClass('Over');

			});

		});

	}

	$('.ProductList li:last-child').addClass('LastChild');

}



$(document).ready(function() {

	$('.InitialFocus').focus();

	$('table.Stylize tr:first-child').addClass('First');

	$('table.Stylize tr:last-child').addClass('Last');

	$('table.Stylize tr td:odd').addClass('Odd');

	$('table.Stylize tr td:even').addClass('Even');

	$('table.Stylize tr:even').addClass('Odd');

	$('table.Stylize tr:even').addClass('Even');

	

	$('.TabContainer .TabNav li').click(function() {

		$(this).parent('.TabNav').find('li').removeClass('Active');

		$(this).parents('.TabContainer').find('.TabContent').hide();

		$(this).addClass('Active');

		$(this).parents('.TabContainer').find('#TabContent'+this.id).show();

		$(this).find('a').blur();

		return false;

	});

	

});







/*--------------------------------------------------------------------------------------------*/





/* Quick search */

var QuickSearch = {

	minimum_length: 3,

	search_delay: 125,

	cache: new Object(),

	init: function()

	{

		$('#search_query').bind("keydown", QuickSearch.on_keydown);

		$('#search_query').bind("keyup", QuickSearch.on_keyup);

		$('#search_query').blur(QuickSearch.on_blur);

		$('#search_query').attr('autocomplete', 'off');



		QuickSearch.path = ("/javascript/../");



	},



	on_blur: function(event)

	{

		if(!QuickSearch.item_selected && !QuickSearch.over_all)

		{

			QuickSearch.hide_popup();

		}

	},



	on_keydown: function(event)

	{

		if(event.keyCode == 13 && !event.altKey)

		{

			if(QuickSearch.selected)

			{

				try {

					event.preventDefault();

					event.stopPropagation();

				} catch(e) { }

				window.location = QuickSearch.selected.url;

				return false;

			}

			else

			{

				QuickSearch.hide_popup();

			}

		}

		else if(event.keyCode == 27)

		{

			if(document.getElementById('QuickSearch'))

			{

				try {

					event.preventDefault();

					event.stopPropagation();

				} catch(e) { }

			}

			QuickSearch.hide_popup();

		}

	},



	on_keyup: function(event)

	{

		if(QuickSearch.timeout)

		{

			clearTimeout(QuickSearch.timeout);

		}



		// Down key was pressed

		if(event.keyCode == 40 && QuickSearch.results)

		{

			if(QuickSearch.selected && QuickSearch.results.length >= QuickSearch.selected.index+1)

			{

				QuickSearch.highlight_item(QuickSearch.selected.index+1, true);

			}

			if(!QuickSearch.selected && QuickSearch.results.length > 0)

			{

				QuickSearch.highlight_item(0, true);

			}

			try {

				event.preventDefault();

				event.stopPropagation();

			} catch(e) { }

			return false;

		}

		else if(event.keyCode == 38 && QuickSearch.results)

		{

			if(QuickSearch.selected && QuickSearch.selected.index > 0)

			{

				QuickSearch.highlight_item(QuickSearch.selected.index-1, true);

			}

			try {

				event.preventDefault();

				event.stopPropagation();

			} catch(e) { }

		}

		else if(event.keyCode == 27)

		{

			QuickSearch.hide_popup();

		}

		else

		{

			if($('#search_query').val() == QuickSearch.last_query)

			{

				return false;

			}

			QuickSearch.selected = false;

			if($('#search_query').val().replace(/^\s+|\s+$/g, '').length >= QuickSearch.minimum_length)

			{

				QuickSearch.last_query = $('#search_query').val().replace(/^\s+|\s+$/g, '');

				if(QuickSearch.timeout)

				{

					window.clearTimeout(QuickSearch.timeout);

				}

				QuickSearch.timeout = window.setTimeout(QuickSearch.do_search, QuickSearch.search_delay);

			}

			else {

				if(document.getElementById('QuickSearch'))

				{

					$('#QuickSearch').remove();

				}

			}

		}

	},



	do_search: function()

	{

		var cache_name = $('#search_query').val().length+$('#search_query').val();

		if(QuickSearch.cache[cache_name])

		{

			QuickSearch.search_done(QuickSearch.cache[cache_name]);

		}

		else

		{

			$.ajax({

				type: 'GET',

				url: QuickSearch.path+'search.php?action=AjaxSearch&search_query='+encodeURIComponent($('#search_query').val()),

				success: function(response) { QuickSearch.search_done(response); }

			});

		}

	},



	search_done: function(response)

	{

		// Cache results

		var cache_name = $('#search_query').val().length+$('#search_query').val();

		QuickSearch.cache[cache_name] = response;



		if(window.ActiveXObject)

		{

			var results_xml = new ActiveXObject("Microsoft.XMLDOM");

			results_xml.async = false;

			results_xml.loadXML(response);

		}

		else

		{

			var _parser = new DOMParser();

			var results_xml = _parser.parseFromString(response, "text/xml");

		}

		// Parse in results

		var results = results_xml.getElementsByTagName('result');

		if(results && results.length > 0)

		{

			QuickSearch.results = new Array();

			for(var i = 0; i < results.length; i++)

			{

				QuickSearch.results.push({

					title: results[i].getAttribute('title'),

					url: results[i].getAttribute('url'),

					price: results[i].getAttribute('price'),

					ratingimg: results[i].getAttribute('ratingimg'),

					image: results[i].getAttribute('image')

				});

			}





			// Results are now stored, build the menu



			if(document.getElementById('QuickSearch'))

			{

				$('#QuickSearch').remove();

			}



			var popup_container = document.createElement('TABLE');

			popup_container.className = 'QuickSearch';

			popup_container.id = 'QuickSearch';

			popup_container.cellPadding = "0";

			popup_container.cellSpacing = "0";

			popup_container.border = "0";



			var popup = document.createElement('TBODY');

			popup_container.appendChild(popup);



			// Initial node is our "Products" node

			var tr = document.createElement('TR');

			var td = document.createElement('TD');

			tr.className = "QuickSearchTitle";

			td.colSpan = "2";

			td.innerHTML = results_xml.getElementsByTagName('results')[0].getAttribute('type');

			tr.appendChild(td);

			popup.appendChild(tr);



			for(var i = 0; i < QuickSearch.results.length; i++)

			{

				var result = QuickSearch.results[i];

				var tr = document.createElement('TR');

				tr.id = "QuickSearchResult"+i;

				tr.className = "QuickSearchResult";



				var image_container = document.createElement('TD');

				image_container.className = 'QuickSearchResultImage';



				result.image = unescape(result.image);

				if(result.image.indexOf('http://') == 0 || result.image.indexOf('https://') == 0)

				{

					var image = document.createElement('IMG');

					image.src = result.image;

					image.alt = '';

					image.title = unescape(result.title);

					image_container.appendChild(image);

				}

				else

				{

					image_container.className += " QuickSearchResultNoImage";

					image_container.innerHTML = result.image.replace('+', ' ');

				}

				tr.appendChild(image_container);



				var meta = document.createElement('TD');

				meta.className = "QuickSearchResultMeta";



				var link = document.createElement('A');

				link.className = "QuickSearchResultName";

				link.title = unescape(result.title);

				link.href = result.url;

				link.innerHTML = unescape(result.title);

				meta.appendChild(link);



				var price = document.createElement('span');

				price.className = "Price";

				price.innerHTML = unescape(result.price);

				meta.appendChild(price);



				if(result.ratingimg)

				{

					var rating = document.createElement('IMG');

					rating.className = "RatingIMG";

					rating.src = unescape(result.ratingimg);

					meta.appendChild(rating);

				}



				tr.url = result.url;

				tr.index = i;

				tr.appendChild(meta);

				popup.appendChild(tr);



				tr.onmouseover = function() { QuickSearch.item_selected = true; QuickSearch.highlight_item(this.index, false); };

				tr.onmouseup = function() { window.location = this.url; };

				tr.onmouseout = function() { QuickSearch.item_selected = false; QuickSearch.unhighlight_item(this.index) };

			}



			// More results than we're showing?

			var all_results = results_xml.getElementsByTagName('results')[0].getAttribute('view_all');

			if(all_results)

			{

				var tr = document.createElement('TR');

				var td = document.createElement('TD');

				tr.className = "QuickSearchAllResults";

				tr.onmouseover = function() { QuickSearch.over_all = true; };

				tr.onmouseout = function() { QuickSearch.over_all = false; };

				td.colSpan = 2;

				td.innerHTML = all_results;

				tr.appendChild(td);

				popup.appendChild(tr);

			}



			var clone = popup.cloneNode(true);

			document.body.appendChild(clone);

			clone.style.top = "10px";

			clone.style.left = "10px";

			offset_height = clone.offsetHeight;

			offset_width = clone.offsetWidth;

			clone.parentNode.removeChild(clone);



			add_offset_left = 50;

			

			var offset_top = offset_left = -add_offset_left;

			var element = document.getElementById('search_query');



			offset_top = -3;

			do

			{

				offset_top += element.offsetTop || 0;

				offset_left += element.offsetLeft || 0;

				element = element.offsetParent;

			} while(element);



			popup_container.style.position = "absolute";

			popup_container.style.left = offset_left + 1 + "px";

			popup_container.style.top = offset_top + document.getElementById('search_query').offsetHeight + "px";

			if(typeof(QuickSearchWidth) != 'undefined') {

				popup_container.style.width = QuickSearchWidth;

			}

			else {

				popup_container.style.width = document.getElementById('search_query').offsetWidth - 2 + add_offset_left + "px";

			}

			if($('#QuickSearch'))

			{

				$('#QuickSearch').remove();

			}

			document.body.appendChild(popup_container);

			popup_container.style.display = '';

		}

		else

		{

			if(document.getElementById('QuickSearch'))

			{

				$('#QuickSearch').remove();

			}

		}

	},





	hide_popup: function()

	{

		$('#QuickSearch').remove();

		QuickSearch.selected = null;

	},



	highlight_item: function(index, keystroke)

	{

		element = $('#QuickSearchResult'+index);

		if(keystroke == true)

		{

			if(QuickSearch.selected) QuickSearch.selected.className = 'QuickSearchResult';

			QuickSearch.selected = document.getElementById('QuickSearchResult'+index);

		}

		element.addClass("QuickSearchHover");

	},



	unhighlight_item: function(index)

	{

		element = $('#QuickSearchResult'+index);

		element.removeClass('QuickSearchHover');

	}

};



$(document).ready(function()

{

	QuickSearch.init();

});

/* end of Quick search */



/*--------------------------------------------------------------------------------------------*/



/*

 * JTip

 * By Cody Lindley (http://www.codylindley.com)

 * Under an Attribution, Share Alike License

 * JTip is built on top of the very light weight jquery library.

 */



//on page load (as soon as its ready) call JT_init

$(document).ready(JT_init);



var JT_rmdelay = 2000;

var JT_rmflag = false;

var JT_linkId = 0;

var JT_timerid = 0



function JT_init(){

	       $("a.jTip")

		   .hover(function(){},function(){ JT_remove();})

           .click(function(){JT_show(this.href,this.id,this.name); return false});	   

}



function JT_remove(){

	if(JT_timerid)

		clearTimeout(JT_timerid);

	JT_rmflag = true;

	JT_timerid = setTimeout(function() {

		if(JT_rmflag) {

			JT_remove_now();

		}

	}, JT_rmdelay); 

}



function JT_remove_now(){

	$('#JT').remove();

	JT_rmflag=false;

	JT_linkId = 0;

}



function JT_show(url,linkId,title){

	if(linkId == JT_linkId) {

		JT_rmflag = false;

		return;

	}

	

	JT_linkId = 0;	

	if($('#JT')) $('#JT').remove();

	JT_rmflag = false;

	

	if(title == false)title="&nbsp;";

	var de = document.documentElement;

	var w = self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;

	var hasArea = w - getAbsoluteLeft(linkId);

	var clickElementy = getAbsoluteTop(linkId) - 3; //set y position

	

	var queryString = url.replace(/^[^\?]+\??/,'');

	var params = parseQuery( queryString );

	if(params['width'] === undefined){params['width'] = 250};

	if(params['link'] !== undefined){

	$('#' + linkId).bind('click',function(){window.location = params['link']});

	$('#' + linkId).css('cursor','pointer');

	}

	

	if(hasArea>((params['width']*1)+75)){

		$("body").append("<div id='JT' onmouseover = 'JT_rmflag = false;' onmouseout = 'JT_remove();' style='width:"+params['width']*1+"px'><div id='JT_arrow_left'></div><div id='infoBox'><div class='hd'><div class='c'></div></div><div class='bd'><div class='shadowRight'></div><div class='c'><div style='float:right;margin:-10px 0 14px 0'><a href='#' onclick='JT_remove_now(); return false;'><img src='/templates/default/images/new/close.gif' width='9px' height='10px' alt='"+lang.close+"'></a></div><div id='JT_copy'><div class='JT_loader'></div></div></div></div><div class='shadowCorner'></div><div class='ft'></div></div></div>");//right side

		var arrowOffset = getElementWidth(linkId) + 11;

		var clickElementx = getAbsoluteLeft(linkId) + arrowOffset; //set x position

	}else{

		$("body").append("<div id='JT' onmouseover = 'JT_rmflag = false;' onmouseout = 'JT_remove();' style='width:"+params['width']*1+"px'><div id='JT_arrow_right' style='left:"+((params['width']*1)+1)+"px'></div><div id='infoBox'><div class='hd'><div class='c'></div></div><div class='bd'><div class='shadowRight'></div><div class='c'><div style='float:right;margin:-10px 0 14px 0'><a href='#' onclick='JT_remove_now(); return false;'><img src='/templates/default/images/new/close.gif' width='9px' height='10px' alt='"+lang.close+"'></a></div><div id='JT_copy'><div class='JT_loader'></div></div></div></div><div class='shadowCorner'></div><div class='ft'></div></div></div>");//left side

		var clickElementx = getAbsoluteLeft(linkId) - ((params['width']*1) + 15); //set x position

	}

	

	$('#JT').css({left: clickElementx+"px", top: clickElementy+"px"});

	$('#JT').show();

	$('#JT_copy').load(url);

	JT_linkId = linkId;

	//JT_remove();

//	$('#JT')



}



function getElementWidth(objectId) {

	x = document.getElementById(objectId);

	return x.offsetWidth;

}



function getAbsoluteLeft(objectId) {

	// Get an object left position from the upper left viewport corner

	o = document.getElementById(objectId)

	oLeft = o.offsetLeft            // Get left position from the parent object

	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element

		oParent = o.offsetParent    // Get parent object reference

		oLeft += oParent.offsetLeft // Add parent left position

		o = oParent

	}

	return oLeft

}



function getAbsoluteTop(objectId) {

	// Get an object top position from the upper left viewport corner

	o = document.getElementById(objectId)

	oTop = o.offsetTop            // Get top position from the parent object

	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element

		oParent = o.offsetParent  // Get parent object reference

		oTop += oParent.offsetTop // Add parent top position

		o = oParent

	}

	return oTop

}



function parseQuery ( query ) {

   var Params = new Object ();

   if ( ! query ) return Params; // return empty object

   var Pairs = query.split(/[;&]/);

   for ( var i = 0; i < Pairs.length; i++ ) {

      var KeyVal = Pairs[i].split('=');

      if ( ! KeyVal || KeyVal.length != 2 ) continue;

      var key = unescape( KeyVal[0] );

      var val = unescape( KeyVal[1] );

      val = val.replace(/\+/g, ' ');

      Params[key] = val;

   }

   return Params;

}



function blockEvents(evt) {

              if(evt.target){

              evt.preventDefault();

              }else{

              evt.returnValue = false;

              }

}

/* end of Jtip */



/*-----------------------------------------------------------------------------------*/

/* Index.js */

var resizeTimer = null;



$(document).ready(function(){

	

	$(window).bind('resize', function() {

		if (resizeTimer) clearTimeout(resizeTimer);

		resizeTimer = setTimeout(on_resize, 500);

	});   

	

	$("#offers").find("div.col:last").css({'border': 'none'});



	$("div.top5").each(function(){

		$(this).find("ol li:first").addClass("firstplace");

	});

				

	$("div.header ul li:last").addClass("last");

//	$("div.url_string").animate({opacity: "0.6"}, "slow");



	var height = $("div.top_banner").height();

	$("div.top_part").css({'margin-top': height});

//	$("ul.products_menu").animate({marginTop: height+130});

	$("div.search ul li:first").addClass("first");

	

	if($('.goods')){

		goods_resize();

	}

	resize_right_column();
	resize_left_column();

});



function on_resize() {

	if($('.goods')){

		goods_clear_sizes();

		goods_resize();

	}

	resize_right_column();

}



function goods_clear_sizes(){

   $(".goods .goods_pic").each(function(){

				  $(this).css({'height': '' });

				  $(this).find("img").css({'margin-top': ''});			

				});

   $(".goods .goods_caption").each(function(){

				  $(this).css({'height': '' });

				});

   $(".goods .parameters").each(function(){

				  $(this).css({'height': '' });

				});

   $(".goods .descr").each(function(){

				  $(this).css({'height': '' });

				});

}





function goods_resize(){

$('.goods').each(function(){


	var colfirst = $(this).find(".col:first");
if(!colfirst.position()) return;
	var startPos = colfirst.position().left;

	var numPerRow = 0;

	$(this).find(".col").each(function(){ 

		if (numPerRow++ >0 && $(this).position().left == startPos) {numPerRow--; return false} 

	});



	var numRows = Math.ceil($(this).find(".col").size() / numPerRow);

	for (var row = 0; row < numRows; row++) { 

		var rStart = row*numPerRow;

		var rEnd = row*numPerRow+numPerRow;



		var myGoodsPic = $(this).find(".goods_pic").slice(rStart, rEnd);

		var myGoodsCaption = $(this).find(".goods_caption").slice(rStart, rEnd);

		var myGoodsParams = $(this).find(".parameters").slice(rStart, rEnd);

		var myGoodsDescr = $(this).find(".descr").slice(rStart, rEnd);



		var goodsHeight=0;

		myGoodsPic.each(function(){

			if ( $(this).height() > goodsHeight) { goodsHeight = $(this).height(); } 

		});



		myGoodsPic.each(function(){

			$(this).css({'height': goodsHeight });

			var ourGoods = $(this).find("img").height();

			var ourMargin = (goodsHeight - ourGoods)/1.7;

			$(this).find("img").css({'margin-top': ourMargin });			

		});

		var captionHeight=0;

		myGoodsCaption.each(function(){

			if ( $(this).height() > captionHeight) {  captionHeight = $(this).height(); } 

		});



		myGoodsCaption.each(function(){ $(this).css({'height': captionHeight }); });



		var parHeight=0;

		myGoodsParams.each(function(){

			if ( $(this).height() > parHeight) {  parHeight = $(this).height(); } 

		});



		myGoodsParams.each(function(){  				

			$(this).css({'height': parHeight });

		});



		var descrHeight=0;

		myGoodsDescr.each(function(){

			if ( $(this).height() > descrHeight){ descrHeight = $(this).height(); } 

		});



		myGoodsDescr.each(function(){

			$(this).css({'height': descrHeight });

		});

	};

});

}



function resize_right_column(){

   $("div.main").css('height','');

   $("div.right").css('height','');

   var contentht = $("div.main").height();

   var rightht = $("div.right").height();

   if (contentht > rightht) { 

 	  $("div.right").height(contentht+2);

   } else {

 	  $("div.main").height(rightht-2);

   }

}



function resize_left_column(){

   $("div.main").css('height','');

   $("div.left").css('height','');

   var contentht = $("div.main").height();

   var rightht = $("div.left").height();

   if (contentht > rightht) { 

 	  $("div.left").height(contentht+2);

   } else {

 	  $("div.main").height(rightht-2);

   }

}

/* end of index.js */

