$(document).ready(function(){
	if($.browser.msie && $.browser.version <= 6){
		//$(window).load(function(){ if($().pngFix){ $(document).pngFix(); } });
		$(document).pngFix();
		
		$("#dialogbox-transparency").css({ "width": $(window).width(), "height": $(document).height() });
		$("#dialogbox-transparency").fadeIn(100);	
		$("#dialogbox-transparency").fadeTo(100, 0.8);	
		$("#dialogbox").css("top",  $(window).height() / 2 - $("#dialogbox").height() / 2);
		$("#dialogbox").css("left", $(window).width() / 2 - $("#dialogbox").width() / 2);
		$("#dialogbox").fadeIn(100);
		$(function(){ $("#dialogbox").pngFix(); });
	}
	
	// cart
	$("#cart #cart-content").mouseenter(function(){
		$("#view_products_cart").css("display", "block");
		$("#cart .scroll-pane").jScrollPane();
		$("#view_products_cart").css("height", "auto");
	});
	$("#cart #cart-content").mouseleave(function(){ $("#view_products_cart").css("display", "none"); });
	
	$("input").attr("autocomplete", "off");
	//$('input[name="product_ID"]').attr("autocomplete", "off");
	
	rollover_image(".prerollover");
	
	if($("a[rel='image']").length > 0) $("a[rel='image']").colorbox({ transition: "fade" });
	
	if($("#detailed-item").length > 0) font_size_changer("#detailed-item", "news", 11, 13);
	
	screenshotPreview();
	
	if($(".products-tabs").length > 0){
		$(".products-tabs-list a").mouseover(function(){ switch_tabs($(this)); });
		switch_tabs($(".defaulttab"));
	}
	
	if($(".toggle-catalog-categories").length > 0){
		$(".toggle-catalog-categories").hide();
		$("h2.cattrigger").click(function(){
			$(this).toggleClass("active").next().slideToggle("fast");
			$(this).siblings().next("div.toggle-catalog-categories").toggleClass("active").slideUp("fast");
		});
	}
	
	$(".label_check, .label_radio").click(function(){ customLabel(); });
	customLabel();
});

/* functions */

function findPos(obj){
    var curleft = curtop = 0;
    if (obj && obj.offsetParent){
	    do{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

function get_price_decimals(price){
	price += "";
	
	if(price.split(".").length < 2) price += ".00"; 
	
	var x = price.split(".");
	var x1 = x[0];
	x2 = x.length > 1 ? "." + x[1] : "";
	var rgx = /(\d+)(\d{3})/;
	
	while(rgx.test(x1)) x1 = x1.replace(rgx, "$1" + "." + "$2");
	x = x1 + x2;
	
	return x.replace(/(\.)([0-9]*)$/, ",<sup>$2</sup>");
}

/*$*$*$*$* rollover image */

function rollover_image(hierarchy_elements){
	// Preload all rollovers
	$(hierarchy_elements + " img").each(function(){
		// Set the original src
		rollsrc = $(this).attr("src");
		rollON = rollsrc.replace(/.png$/ig,"-h.png");
		$("<img>").attr("src", rollON);
	});
	
	// Navigation rollovers
	$(hierarchy_elements + " a").mouseover(function(){
		imgsrc = $(this).children("img").attr("src");
		matches = imgsrc.match(/-h/);
		
		// don't do the rollover if state is already ON
		if (!matches){
			imgsrcON = imgsrc.replace(/.png$/ig,"-h.png"); // strip off extension
			$(this).children("img").attr("src", imgsrcON);
		}
		
	});
	$(hierarchy_elements + " a").mouseout(function(){
		$(this).children("img").attr("src", imgsrc);
	});
}

/*$*$*$*$* content rotator */

function setupRotator(container, item, duration){
	if($(item).length > 1){
		$(item + ":first").addClass("current").fadeIn(1000);
		setInterval("contentRotate('" + container + "', '" + item + "')", duration);
	}
}
function contentRotate(container, item){
	var current = $(container + " > .current");
	if(current.next().length == 0){
		current.removeClass("current").fadeOut(1000);
		$(item + ":first").addClass("current").fadeIn(1000);
	}else{
		current.removeClass("current").fadeOut(1000);
		current.next().addClass("current").fadeIn(1000);
	}
}

/*$*$*$*$* tabs */

function switch_tabs(obj){
	$(".tabprod").hide();
	$(".products-tabs-list a").removeClass("selected");
	var id = obj.attr("rel");
	$(id).show();
	obj.addClass("selected");
}

/*$*$*$*$* custom radio/checkbox */

function customLabel(){
	if($(".label_check input").length){
		$(".label_check").each(function(){ $(this).removeClass("c_on"); });
		$(".label_check input:checked").each(function(){ $(this).parent("label").addClass("c_on"); });                
	};
	if($(".label_radio input").length){
		$(".label_radio").each(function(){ $(this).removeClass("r_on"); });
		$(".label_radio input:checked").each(function(){ $(this).parent("label").addClass("r_on"); });
	};
}

/*$*$*$*$* j utils */

function chars_left(limitField, limitCount, limitNum){
	if(limitField.value.length > limitNum){
		limitField.value = limitField.value.substring(0, limitNum);
	}else{
		limitCount.value = limitNum - limitField.value.length;
	}
}

function submitenter(myfield, e){
	var keycode;
	
	if(window.event){
		keycode = window.event.keyCode;
	}else if(e){
		keycode = e.which;
	}else return true;
	
	if(keycode == 13){
		myfield.form.submit();
		return false;
	}else return true;
}

/*$*$*$*$* submit form */

function testKeyword(form, field_name, keyword_form, alert_message){
	var keyword = document.forms[form][field_name].value;
	var trimmed = keyword.replace(/^\s+|\s+$/g, "");
	
	if(trimmed.length == 0 || keyword == keyword_form){
		alert(alert_message);
		return false;
	}
	
	return true;
}

function submit_form(form, field_name, keyword, alert_message){
	if(testKeyword(form, field_name, keyword, alert_message) == true) document.forms[form].submit();
}

function submit_enter(object, event, form, field_name, keyword, alert_message){
	var keycode;
	
	if(window.event){
		keycode = window.event.keyCode;
	}else if(event){
		keycode = event.which;
	}else{
		return true;
	}

	if (keycode == 13){
		submit_form(form, field_name, keyword, alert_message);
		return false;
	}
	
	return true;
}

/*$*$*$*$* cookies */

function createCookie(name,value,days){
	var expires;
	if(days){
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}else{
		expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(";");
	for(var i = 0; i < ca.length; i++){
		var c = ca[i];
		while(c.charAt(0) == " ") c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name){
	createCookie(name, "", -1);
}

/*$*$*$*$* font size changer */

function decreaseFont(container, unique_id, min_size){
	var currentFontSize = container.css("font-size");
	var currentFontSizeNum = parseInt(currentFontSize, 10);
	if(currentFontSizeNum > min_size)
	var newFontSize = currentFontSizeNum - 1;
	container.css("font-size", newFontSize);
	createCookie("text_size_" + unique_id, container.css("font-size"), 7);	
	return false;
}

function increaseFont(container, unique_id, max_size){
  	var currentFontSize = container.css("font-size");
 	var currentFontSizeNum = parseInt(currentFontSize, 10);
	if(currentFontSizeNum < max_size)
    var newFontSize = currentFontSizeNum + 1;
	container.css("font-size", newFontSize);
	createCookie("text_size_" + unique_id, container.css("font-size"), 7);	
	return false;
}

function font_size_changer(target_area, unique_id, min_size, max_size){
	if(readCookie("text_size_" + unique_id) == null) createCookie("text_size_" + unique_id, $(target_area).css("font-size"), 7);
	if(readCookie("o_text_size_" + unique_id) == null) createCookie("o_text_size_" + unique_id, $(target_area).css("font-size"), 7);
	$(target_area).css("font-size", readCookie("text_size_" + unique_id));
	
	// Increase Font Size
	$(".increaseFont").click(function(){ increaseFont($(target_area), unique_id, max_size); });
	// Decrease Font Size
	$(".decreaseFont").click(function(){ decreaseFont($(target_area), unique_id, min_size); });
}

/*$*$*$*$* input limits */

function decrement_value(id_input, min_value){
	var input = document.getElementById(id_input);
	if(input.value > min_value){ input.value--; }
	if(input.value == ""){ input.value = min_value; }
}

function increment_value(id_input, max_value){
	var input = document.getElementById(id_input);
	if(input.value < max_value){ input.value++; }
	if(input.value == ""){ input.value = min_value; }
}

function toBeBetween(input, min_value, max_value){
	if(parseInt(input.value) > max_value){ input.value = max_value; }
	if(parseInt(input.value) < min_value){ input.value = min_value; }
}

function limitText(limitField, maxVal){
	var maxValLen = (maxVal + "").length;
	
	if(parseInt(limitField.value) < 0){
		limitField.value = 0;
	}
	
	if(limitField.value.length >= maxValLen){
		limitField.value = limitField.value.substring(0, maxValLen);
		
		if(limitField.value > maxVal){
			limitField.value = limitField.value.substring(0, maxValLen - 1);
		}
		if(limitField.value == maxVal){
			limitField.value = maxVal;
		}
	}
}

function numbersonly(e, decimal){
	var key;
	var keychar;

	if(window.event){
		key = window.event.keyCode;
	}else if(e){
		key = e.which;
	}else{
		return true;
	}
	
	keychar = String.fromCharCode(key);
	
	if((key == null) || (key == 0) || (key == 8) ||  (key == 9) || (key == 13) || (key == 27)){
		return true;
	}else if((("0123456789").indexOf(keychar) > -1)){
		return true;
	}else if(decimal && (keychar == ".")){
		return true;
	}else{
		return false;
	}
}

/*$*$*$*$* open pop-up windows */

var WindowObjectReference = null; // global variable

function openRequestedPopup(strUrl, strWindowName, width, height){
	var wleft = parseInt((screen.availWidth/2) - (width/2));
	var wtop = parseInt((screen.availHeight/2) - (height/2));
	
	// IE5 and other old browsers might allow a window that is partially offscreen or wider than the screen. Fix that.
	if (wleft < 0){
		w = screen.width; wleft = 0;
	}
	if (wtop < 0){
		h = screen.height; wtop = 0;
	}
	
	if(WindowObjectReference == null || WindowObjectReference.closed){
		WindowObjectReference = window.open(strUrl, strWindowName, "width=" + width + ",height=" + height + ",menubar=1,resizable=no,left=" + wleft + ",top=" + wtop + ",scrollbars=yes,status=yes");
	}else{
		WindowObjectReference.focus();
	}
}

/*$*$*$*$* search with autocomplete */

function fancy_autocomplete_lookup(suggestionsObj, url, min_letters_lookup, form_class, autocomplete_empty_msg){
	if(suggestionsObj.find("input.inputString").val().length == 0){
		suggestionsObj.find(".suggestionsBox").hide();
	}else{
		var regex = /^[1-9]{1}$/;
		min_letters_lookup_for = regex.exec(min_letters_lookup) ? min_letters_lookup : 3;
		if($("input.inputString").val().length >= min_letters_lookup_for){
			$.ajax({
				type: "POST",
				url: url,
				data: "op=autosuggest&queryString=" + suggestionsObj.find("input.inputString").val(),
				success: function(msg){
					if(msg && msg != ""){
						var respObj = msg.split("|");
						if(respObj && respObj.length > 0){
							suggestionsObj.find(".suggestionsBox").show();
							suggestionsObj.find(".suggestionList").html("<ul></ul>");
							for(var i in respObj){
								var respObjElem = respObj[i].split("###");
								suggestionsObj.find(".suggestionList ul").append("<li>" + respObjElem[1] + "</li>");
								suggestionsObj.find(".suggestionList ul li:last").bind("click", { param: { "target_id" : suggestionsObj.children("input.inputString").attr("id"), "id" : respObjElem[0], "name" : respObjElem[1], "form_class" : form_class } }, function(event){
									fancy_autocomplete_fill({ "target_id" : event.data.param.target_id, "id" : event.data.param.id , "name": event.data.param.name, "form_class": event.data.param.form_class });
								});
							}
						}
					}else{
						suggestionsObj.find(".suggestionsBox").show();
						suggestionsObj.find(".suggestionList").html(autocomplete_empty_msg);
					}
				}
			});
		}else{
			setTimeout("$('.suggestionsBox').hide();", 200);
		}
	}
}

function fancy_autocomplete_fill(param){
	if(param.name && param.id && param.form_class){
		$("#" + param.target_id).parent().find("input.inputString").val(param.name);
		$("." + param.form_class).find("input[type='hidden'][name='" + param.target_id + "_hidden']").val(param.id);
		$("." + param.form_class).find("input[type='hidden'][name='id_product']").val(param.name);
		$(".autocompletesender").submit();
	}
}

function fancy_autocomplete_init_suggestions(obj, url, min_letters_lookup, form, autocomplete_msg, autocomplete_empty_msg){
	$(".fancyautocomplete input").attr("autocomplete", "off");
	obj.each(function(){
		var _this = $(this);
		
		_this.append(
			'<div class=\"suggestionsBox\">' +
			autocomplete_msg +
				'<img src=\"img/icons/suggestions-arrow-list.png\" alt=\"\" class=\"suggestionsArrow\">' +
				'<div class=\"suggestionList max-height-results\"></div>' +
			'</div>'
		);
		
		_this.find("input.inputString").keyup(function(){
			fancy_autocomplete_lookup(_this, url, min_letters_lookup, form.attr("class"), autocomplete_empty_msg);
		});
		_this.find("input.inputString").blur(function(){
			fancy_autocomplete_fill({"target_id" : _this.attr("id")});
			
		});
		
		_this.children(".suggestionsBox").css("width", _this.children("input.inputString").width());
		_this.children(".suggestionsBox").css("left", _this.children("input.inputString").get(0).offsetLeft);
		_this.children(".suggestionsBox").css("top", _this.children("input.inputString").get(0).offsetTop + 2 * _this.children("input.inputString").height());
		_this.find(".suggestionsArrow").css("left", _this.children("input.inputString").width() / 2);
	});
	$("*").click(function(){
		if($(this).attr("class") != "suggestionsBox") setTimeout("$('.suggestionsBox').hide();", 200);
	});
}

/*
 * Url preview script 
 * written by Alen Grakalic (http://cssglobe.com) http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 */
this.screenshotPreview = function(){	
	xOffset = 10;
	yOffset = 30;
	// these 2 variable determine popup's distance from the cursor
	// you might want to adjust to get the right result
	
	$("a.screenshot-tooltip").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='screenshot-tooltip'><img src='" + this.rel + "' alt=''>" + c + "</p>");								 
		$("#screenshot-tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#screenshot-tooltip").remove();
    });	
	$("a.screenshot-tooltip").mousemove(function(e){
		$("#screenshot-tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
	});		
};
