//jQuery.noConflict();
var $j=jQuery;

if(!window.console)
{
	window.console={};
	window.console.log=function(){};
}

var uriPartsRe = new RegExp("^(.+?)://([^/]+?)/([^?]+)(\\?.+)?");
function parseUri(uri)
{
	var p=uriPartsRe.exec(uri);
	if(!p) return null;
	return {protocol:p[1],domain:p[2],path:p[3],params:p[4]};
}

function rpcFailure(xhr,text,error)
{
	alert('Internal error '+xhr.status+' with RPC call.');
}


function rpc(call,opt,cb,post)
{
	if(!opt) opt={};
	if(typeof opt!="string") opt=jQuery.param(opt);
	opt+="&ctx=j&_="+(new Date().getTime());
	if(opt[0]=="?") opt=opt.substr(1);
	if(post) method="post";
	else method="get";
	$j.ajax({
		type: method,
		data: opt,
		dataType: 'json',
		success:
			function(data,textStatus)
			{
				$(".rpc_loading").remove();
				if(data.error)
				{
					if(data.showErrorInDialog) {
						showGenericDialog(data.error);
					} else {
						alert(data.error);
					}
					return false;
				}
				if(data.cb && typeof(window[data.cb]) != "undefined") cb=window[data.cb];
				if(cb) return cb(data, textStatus);
				return false;
			},
		error: rpcFailure,
		url: '/r/'+call
	});
}

function showLoadingIndicator(event) {
	$(".rpc_loading").remove();
	var pos = null;
	if(event.pageX && event.pageY) pos = {top: event.pageX, left: event.pageY};
	if(event.type == "submit") {
		var subm = $("input[type=submit]", event.target);
		if(subm.length) {
			pos = subm.offset();
			pos.left += 9 + subm.width();
		}
	}
	if(pos.top && pos.left) {
		$("<div>", {
			"class":	"rpc_loading",
			"css":	{
				"background":	"url(/static/shop_loading.gif) no-repeat",
				"width":		16,
				"height":		16,
				"position":		"absolute",
				"z-index":		600,
				"left":			pos.left,
				"top":			pos.top
			}
		}).appendTo("body");
	}
}

function rpcClickHandler(event)
{
	
	var up=parseUri(this.href);
	var call=up.path.substr(2);
	var cb;
	var cbName=call+"Cb";
	if(typeof window[cbName]!='undefined') cb=window[cbName];
	else cb=null;
	rpc(call,up.params,cb);
	showLoadingIndicator(event);

	return false;
}

/**
 * Initializes the RPC system, making URLs that begin with "r/" (for request or RPC, you pick),
 * with JavaScript RPC calls, UNLESS the rel attribute of the link contains "st" for static.
 */
function initRpc(context)
{
	if(!context) context=null;
	$j('a', context).each(function()
	{
		var L=jQuery(this);
		if(!L.data("rpcd"))
		{
			var up=parseUri(this.href);
			if(up&&up.path.indexOf('r/')==0&&this.rel.indexOf("st")==-1)
			{
				L.click(rpcClickHandler);
				L.data("rpcd", true);
				//if(console) console.log("Activated link "+this.href+" for RPC.");
			}
		}
	});
}

function objToGetVars(obj)
{
	var getVarsPairs = [];
	for(var key in obj) if(obj[key]) getVarsPairs.push(key.toString()+"="+escape(obj[key].toString()));
	return getVarsPairs.join("&");
}


function initForms()
{
	if(!$j(".basketaddform").data("rpcd"))
	{
		$j(".basketaddform").submit(function(event){
			var rpcName = "add";
			try {
				var urlParts = $j(this).attr("action").split("/");
				rpcName = urlParts[urlParts.length - 1];
			} catch(e) {
				rpcName = "add";
			}
			var getVars = {
				"id":	$j(".baprodid",this).val(),
				"n":	parseInt($j(".bacount",this).val()),
				"text":	$j(".batext",this).val()
			};
			if(isNaN(getVars["n"]) || getVars["n"]<1 || getVars["n"]>10000)
			{
				alert("Epäkelpo määrä!");
				return false;
			}
			
			if($j(".customprefix"))
			{				
				getVars["text_prefix"] = $j(".customprefix").val();
				
			}
			if($j(".customtext"))
			{
				getVars["text"] = $j(".customtext").val();
			}
			if($j(".sticker"))
			{				
				getVars["sticker"] = $j("select.sticker").val();
			}
			
			if(!$j(this).hasClass("no-indicator")) { showLoadingIndicator(event); }
			rpc(rpcName, objToGetVars(getVars), addCb);
			return false;
		}).data("rpcd", true);
	}

	if(!$j(".prodvarform").data("rpcd"))
	{
		$j(".prodvarform").submit(function(event){			
			var vars = {
				"pid":	this.pid.value,
				"n":	$j(".prodvarquant",this).val()				
			};			
			$j("select", this).each(function(){vars[this.name] = this.value;});			
			if($j(".customprefix"))
			{				
				vars["text_prefix"] = $j(".customprefix").val();
				
			}
			if($j(".customtext"))
			{
				vars["text"] = $j(".customtext").val();
			}
			if($j(".sticker"))
			{				
				vars["sticker"] = $j("select.sticker").val();
			}
			showLoadingIndicator(event);			
			rpc("addvar", objToGetVars(vars), addCb, "post");
			return false;
		}).data("rpcd", true);
		
	}
	if($j.browser.msie)
	{
		var elems = $j('.prodvarform select');
		elems.each(function(index,elem){			
			$j(elem).mousedown(function() {
				$j(this).css({'width':'auto','z-index':9999,'position':'relative'});                            
			});
			$j(elem).focusout(function(){
				$j(this).css('width','100%');                            
			});
			$j(elem).change(function() {
				$j(this).css('width','100%');                            
			});
		})
	}
}

function getPartial(targetId,partialName,data)
{
	$j("#"+targetId).load("/t/"+escape(partialName),data);
}


function initStaticPageMenu()
{
	var hostname = window.location.hostname.toString();
	var current = window.location.toString();

	if($("div#static_nav"))
	{
		$("div#static_nav a").filter(function() {
			var thisurl = "http://" + hostname + $(this).attr("href");
			if(current == thisurl) $(this).parent().addClass("active");
		});
	
		$(".static_nav li ul").hide(); 
	
		$(".static_nav li").hover(
			function () { $(this).children("ul").show(); },
			function () { $(this).children("ul").hide(); }
		);
	}
}


function initPage()
{
	if(!window.shopPageInited)
	{
		initRpc();
		initForms();
		initStaticPageMenu(); 
		window.shopPageInited = true;
	}
	//if($("#renew-order").length) $("#renew-order").click(renewOrder);
	
}

function openPopup(href, w, h)
{
	var id = (new Date()).getTime().toString();
	if(!w) w = 400;
	if(!h) h = 500;
	window["page"+id] = window.open(href, id, "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h);
}

function _updateBasketParts(data)
{
	if(data.basket_partial) {
		$j("#basket_content").html(data.basket_partial);
		initRpc("#basket_content");
	}
	if(data.basket_table) {
		$j("#basket_table").html(data.basket_table);
		initRpc("#basket_table");
	}	
}

function addCb(data,textStatus)
{
	return _updateBasketParts(data);
}

function subCb(data,textStatus)
{
	return _updateBasketParts(data);
}

function clearbasketCb(data,textStatus)
{
	return _updateBasketParts(data);
}

function showTextTip(id, text)
{
	$j("#"+id).remove();
	$j("<div id=\""+id+"\" />").html(text).appendTo("body").show().fadeOut(1500);
}

function showBasketTipSoon(text)
{
	setTimeout(function(){showTextTip("basket-tooltip", text)}, 50);
}

function closeGenericDialog()
{
	$("#generic-dialog").fadeOut("fast", function(){
		$(this).remove();
	});
}

//This method is supposed to open a dialog box and display
//the given contents in it.
var bodyClickEventInstalled = false;
var bodyClickShouldRemoveDialog = true;
function showGenericDialog(html_contents)
{
	$j("#generic-dialog").remove();
	bodyClickShouldRemoveDialog = !(html_contents.indexOf("<form ") > -1 || html_contents.indexOf("<a ") > -1);
	
	if(!bodyClickShouldRemoveDialog) {
		html_contents = "<div align=\"right\"><a href=\"#\" onclick=\"closeGenericDialog();return false\">Sulje</a></div>" + html_contents;		
	}
	
	var dialog = $j("<div />", {
		"id":	"generic-dialog",
		"css": 	{
			"position":			"fixed",
			"top":				"50%",
			"left":				"50%",
			"background":		"#ffffff",
			"border":			"1px solid #c3c3c3",
			"padding":			"10px",
			"width":			"400px",
			"margin":			"-15px 0 0 -200px",
			"text-align":		"center",
			"cursor":			"pointer",
			"-moz-box-shadow":	"0 0 25px rgba(0,0,0,.45), 0 0 5px rgba(0,0,0,.2)",
			"z-index":			"9999"
		},
		"html":	html_contents
	}).fadeIn("fast").appendTo("body");
	
	$j("#simple_contact_form_submit").click(function(){
		$.ajax({
			type: 'post',
			url: $j("#simple_contact_form").attr("action"),
			data: $j("#simple_contact_form").serialize(),
			dataType: "json",
			error: function(data) {
				alert("Viestin lähettäminen epäonnistui.");
				return 0;
			},
			success: function(data) {
				if(data.error) {
					alert(data.error);
					return false;
				} else {
					if(data.message) alert(data.message);
					closeGenericDialog();
					return 0;
				}
			}
		});
		
		return false;
	});	
	
	//Prevent dialog removal if there's a link or a form in the content.	
	if(!bodyClickEventInstalled) {
		bodyClickEventInstalled = true;
		$("body").live("click", function(){
			if(bodyClickShouldRemoveDialog) {
				closeGenericDialog();
			}
		});
	}
}

function updateBasketPartials() {
	rpc("getbasket", null, function(data, ts) {
		_updateBasketParts(data);
	});
}

if(jQuery)
{
	jQuery(document).ready(initPage);
}

//function renewOrder(){
//	var rpcName = "add";
//	var rows = []
//	$(".prod-row").each(function(){
//		var id = $(this).attr("id").split("-")[2]
//		var quantity = $(this).children("td.quantity").html()
//		rows.push({id:id,count:quantity})
//		// check if product is available with the quantity, return available quantity		
//	});
//	
//	
//	$.ajax({
//		type: 'get',
//		url: "/tuotteet/saatavuus/",
//		data: {"rows":JSON.stringify(rows)},
//		dataType: "json",
//		success: function(data) {
//			$(data).each(function(){
//				if (!this.error){
//					//console.log(this.count, this.id);				
//					var getVars = {
//						"id":	this.id,
//						"n":	parseInt(this.count),
//						"text":	this.name
//					};
//					rpc(rpcName, objToGetVars(getVars), addCb);
//					console.log("reordered " +this.name)
//				}
//				else {
//					console.log("cannot re-order product: "+this.name)
//				}
//			});
//		}
//	});
//}

