﻿ //////////////////////////
// onload jquery functions
//////////////////////////
$(document).ready(function (e) {
	// activate lightbox, if available:
	$('a.lightbox').lightBox();


});

function popup_close() {
	$('div#popup').fadeOut(1000);	
}

function update_total_with_additional_variables() {
	var add = 0;
	var price = 0;
	$(".extra_variables :input").each(function (e) {
		if ($(this).attr("type") == "checkbox") {
			if ($(this).is(':checked')) {
				val = $(this).val();
			}
		}
		else {
			val = $(this).val();
		}
		if (val.indexOf('+') > -1) {
			if (val.split('+')[1] != "")
				add += parseFloat(val.split('+')[1]);
		}
	});

	if (orig_price)
		price = (1*orig_price) + add;
	else
		price = add;

	$("#ph_total").text(price);
}


//////////////////////////
// cart functions
//////////////////////////
function addToSamples(id) {
	var variant = "";extra = "";
	var failed = false;
	$(".extra_variables :input").each(function (e) {
		if (!failed) {
			extra += (extra != "") ? "|" : "";
			val = $(this).val(); if (val.indexOf('|') > -1) { alert("Sorry, but one of the fields contain '|' which is forbidden here. Please remove it amd try again."); failed = true; return; }

			if (val != "" && $(this).attr("type") != "checkbox")
				extra += $(this).attr("name") + "=" + val;
		}
	});
	if (failed) return;

	// replace + with ~ (urls cant have +)
	extra = extra.replace(/\+/g, '~');
	
	//pageUrl, pageMethodName, async, postData, callBackMethod, objectState
	jPixeliT.Ajax.executePageMethod("Sampleshandler.aspx", "AddItem", true, "compact=true&contentId=" + id + "&extra=" + extra + "&v=" + variant, reloadSamplesView);

	// add checked related items ("you might also want..")
	$(".extra_variables :checkbox:checked").each(function (e) {
		var id = $(this).val();
		if (id.indexOf('+') > -1)	id = id.split('+')[0];

		jPixeliT.Ajax.executePageMethod("Sampleshandler.aspx", "AddItem", true, "compact=true&contentId=" + id + "&v=", reloadSamplesView);
	});
}

// Samples view
function reloadSamplesView(text) {
	$("#cart").html(text);
}
function updateQuantitySamples(element) {
	jPixeliT.Ajax.executePageMethod("Sampleshandler.aspx", "UpdateItemQuantity", true, "compact=true&contentId=" + element.getAttribute("itemId") + "&newQuantity=" + element.value, reloadSamplesView);
}

function removeItemSamples(id) {
	jPixeliT.Ajax.executePageMethod("Sampleshandler.aspx", "RemoveItem", true, "compact=true&contentId=" + id, reloadSamplesView);
}
// order view
function reloadOrderView(text) {
	$("#order").html(text);
}
function updateOrderQuantity(element) {
	jPixeliT.Ajax.executePageMethod("Sampleshandler.aspx", "UpdateItemQuantity", true, "compact=false&contentId=" + element.getAttribute("itemId") + "&newQuantity=" + element.value, reloadOrderView);
}

function removeOrderItem(id) {
	jPixeliT.Ajax.executePageMethod("Sampleshandler.aspx", "RemoveItem", true, "compact=false&contentId=" + id, reloadOrderView);
}


///////////////////////
// remote ajax methods
///////////////////////
// jPixeliT - javascript library v1.2
// Written by Miron Abramson

var undefined, jPixeliT = {
	onError: function (errMessage) {
		alert("jPixeliT error:\n\r " + errMessage);
	}
	,
	//////////////////////////////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////// Ajax ///////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////
	Ajax: {
		Timeout: 40000
		,
		getXhr: function () {
			if (window.ActiveXObject) {
				var msTypes = ['Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
				for (var i = 0, l = msTypes.length; i < l; i++) {
					try {
						return new ActiveXObject(msTypes[i]);
					}
					catch (ex) { }
				}
			}
			return new window.XMLHttpRequest();
		}
		,
		// Determines if an XMLHttpRequest was successful or not
		httpSuccess: function (xhr) {
			try {
				// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
				if ((!xhr.status && location.protocol == "file:" ||
				(xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || xhr.status == 1223) == false) {
					alert(xhr.status); return false;
				}
				return true;
			} catch (e) { alert("httpSuccess:" + e); }
			return false;
		},
		executeWebMethod: function ExecutePageMethod(url, webMethodName, async, postData, callBackMethod, objectState) {
			///	<summary>
			///		Call a static method with attribute '[System.Web.Services.WebMethod]' or a WebService.
			///     To use this method, a ScriptManager control must be place in the aspx code
			///	</summary>
			/// <param name="url" type="String" Mandatory="yes">The url to call</param>
			/// <param name="webMethodName" type="Boolen" Mandatory="yes">Name of the method to excute in the server code</param>
			/// <param name="async" type="Boolen" Mandatory="yes">Excute the call async or sync</param>
			/// <param name="postData" type="String" Mandatory="no">The post data. Must be JSON format !</param>
			/// <param name="callBackMethod" type="function(String,object)" Mandatory="no">The client side mathod to call after the call was completed</param>
			/// <param name="objectState" type="object" Mandatory="no">Object to identify the caller</param>
			var fixedUrl = url;
			var queryString = '';
			var qsStart = url.indexOf('?');
			if (qsStart !== -1) {
				fixedUrl = pageUrl.substr(0, qsStart);
				queryString = url.substr(qsStart);
			}
			fixedUrl += ("/" + encodeURIComponent(webMethodName) + queryString);
			return jPixeliT.Ajax.executeRequest(fixedUrl, async, postData, callBackMethod, objectState, true);
		}
		,
		executePageMethod: function ExecutePageMethod(pageUrl, pageMethodName, async, postData, callBackMethod, objectState) {
			///	<summary>
			///		Excute a method in the code behind in the current page
			///
			/// Drop the following lines in the desired page On_Load event:
			///
			///  // Invoke method that been called from Ajax...
			///  if (Request.PathInfo != null && Request.PathInfo.Length > 1)
			///  {
			///      string methodName = Request.PathInfo.Substring(1);
			///      System.Reflection.MethodInfo theMethod = this.GetType().GetMethod(methodName);
			///      object ret = theMethod.Invoke(this, null);
			///      Response.Clear();
			///      Response.ContentType = "text/plain";
			///      Response.Write(ret);
			///      Response.End();
			///      return;
			///  }
			///
			///	</summary>
			/// <param name="pageUrl" type="Boolen" Mandatory="yes">The page url</param>
			/// <param name="pageMethodName" type="Boolen" Mandatory="yes">Excute the call async or sync</param>
			/// <param name="async" type="Boolen" Mandatory="yes">Excute the call async or sync</param>
			/// <param name="postData" type="String" Mandatory="no">The post data ('name1=value1&name2=value2')</param>
			/// <param name="callBackMethod" type="function(String,object)" Mandatory="no">The client side mathod to call after the call was completed</param>
			/// <param name="objectState" type="object" Mandatory="no">Object to identify the caller</param>
			var url = pageUrl;
			var queryString = '';
			var qsStart = pageUrl.indexOf('?');
			if (qsStart !== -1) {
				url = pageUrl.substr(0, qsStart);
				queryString = pageUrl.substr(qsStart);
			}
			url += ("/" + encodeURIComponent(pageMethodName) + queryString);
			return jPixeliT.Ajax.executeRequest(url, async, postData, callBackMethod, objectState, false);
		}
		,
		executeRequest: function (serverUrl, async, postData, callBackMethod, objectState, isJson) {
			///	<summary>
			///		Access a server url using 'ajax' technic
			///	</summary>
			/// <param name="serverUrl" type="String" Mandatory="yes">The page url to call</param>
			/// <param name="async" type="Boolen" Mandatory="yes">Excute the call async or sync</param>
			/// <param name="postData" type="String" Mandatory="no">The post data ('name1=value1&name2=value2' or JSON format)</param>
			/// <param name="callBackMethod" type="function(String,object)" Mandatory="no">The client side mathod to call after the call was completed</param>
			/// <param name="objectState" type="object" Mandatory="no">Object to identify the caller</param>
			/// <param name="isJson" type="Boolean" Mandatory="no">flag if the request is json os not</param>
			var errMsg = "";
			var xhr = jPixeliT.Ajax.getXhr();
			var type = (!postData && !isJson) ? "GET" : "POST";
			var requestDone = false;
			var status;
			var returnData;
			xhr.open(type, serverUrl, async);
			try {
				xhr.setRequestHeader('jPixeliT-Ajax', 'true');
				if (type === "POST") {
					xhr.setRequestHeader("Content-Type", isJson ? "application/json; charset=utf-8" : "application/x-www-form-urlencoded");
				}
				xhr.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 1970 00:00:00 GMT");
				xhr.setRequestHeader("Cache-Control", "no-cache");
			} catch (e) { }

			// Wait for a response to come back
			var onreadystatechange = function (isTimeout) {
				// The request was aborted, clear the interval 
				if (xhr.readyState == 0) {
					if (intrval) {
						clearInterval(intrval);
						intrval = null;
					}
					// The transfer is complete and the data is available, or the request timed out
				} else if (!requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout")) {
					requestDone = true;
					if (intrval) {
						clearInterval(intrval);
						intrval = null;
					}

					status = (isTimeout == "timeout") ? "timeout" :
					(!jPixeliT.Ajax.httpSuccess(xhr)) ? "error" : "success";

					if (status == "success") {
						try {
							returnData = xhr.responseText ? xhr.responseText : "";
						} catch (e) {
							status = "error"; alert("error: " + e);
						}
					}

					if (isTimeout)
						xhr.abort();

					if (async) {
						xhr = null;
						if (status === "success" && typeof (callBackMethod) === 'function') {
							callBackMethod(returnData, objectState);
						}
						else if (status === "error") {
							jPixeliT.onError("Ajax unknows error");
						}
						else if (status === "timeout") {
							jPixeliT.onError("Ajax request timeout");
						}
					}
					else {
						if (status === "success") {
							return returnData;
						}
						else if (status === "error") {
							jPixeliT.onError("Ajax unknows error");
						}
						else if (status === "timeout") {
							jPixeliT.onError("Ajax request timeout");
						}
					}
				}
			};

			if (async) {
				var intrval = setInterval(onreadystatechange, 13);

				// Timeout checker
				if (jPixeliT.Ajax.Timeout > 0)
					setTimeout(function () {
						// Check to see if the request is still happening
						if (xhr && !requestDone)
							onreadystatechange("timeout");
					}, jPixeliT.Ajax.Timeout);
			}
			// Send the data
			try {
				xhr.send(postData);
			} catch (e) {
				jPixeliT.onError("Ajax request filed. Details: \n\r " + e);
			}

			// firefox 1.5 doesn't fire statechange for sync requests
			if (!async)
				return onreadystatechange();
		}
	}

}
