
var dbScript = "/scripts/databaseHandler.php";

/*
 * Helpers
 */
function show_address_mode(type, address) {
	switch(type) {
		case "uk":
			// show postcode search
			$("#postcode_search_" + address).show();
			break;
		default:
			// hide postcode search
			$("#postcode_search_" + address).hide();
	}
}

function objectLength(obj) {
	var count = 0;
	if(typeof(obj) != "undefined") {
		$.each(obj,function(){
			count++;
		});
	}
	return count;
}

function truncate(string,len) {
	string = string.substring(0,len);
	string += "...";
	return string;
}

/*
 * Basket
 */
(function($) {

	var script = "/scripts/basketHandler.php";
	
	$.basket = {};
	
	$.basket.add = function(product) {

		var qty = $("#product_qty").val();
		var attribute = $("#product_attributes :selected").val();
		var sub_attribute = $("#product_sub_attributes :selected").val();
		var type = $("#product_attributes").attr("lang");

		if(parseInt(attribute)) {
			product = attribute;
		} else if(parseInt(sub_attribute)) {
			product = attribute+"_"+sub_attribute;
			type = $("#product_sub_attributes").attr("lang");
		} else {
			if(!type) {
				type = "product";
			}
		}

		var url = script + "?action=add&product=" + product + "&qty=" + qty + "&type=" + type;
		
		$.getJSON(url, function(data)  {
          	switch(data.result) {
				case "failed":
					alert(data.msg);
					break;
				case "update":
					window.location = "/basket";
					//updateBasket(data.data);
					break;
			}
        });
	}
	
	$.basket.clear = function() {
		$.getJSON(script+"?action=delete",
		function(data)
        {
          	switch(data.result)
			{
				case "failed":
					//alert(data.msg);
					break;
				case "delete":
					window.location.reload();
					break;
			}
        });
	}
	
	$.basket.delete_item = function(product) {
		$.getJSON(script+"?action=delete&product="+product,
		function(data)
        {
          	switch(data.result)
			{
				case "failed":
					//alert(data.msg);
					break;
				case "delete":
					window.location.reload();
					break;
			}
        });
	}
	
	$.basket.get = function() {
		$.getJSON(script+"?action=get",
		function(data)
        {
          	switch(data.result)
			{
				case "failed":
					//alert(data.msg);
					break;
				case "get":
					updateBasket(data.data);
					break;
			}
        });
	}
	
	$.basket.shipping_update = function() {
		var price = $("#shipping_method_id :selected").val();
		if(!price)price = $("#shipping_method_id").val();
		//alert(script+"?action=update_shipping&data="+price);
		$.getJSON(script+"?action=update_shipping&data="+price,
		function(data)
        {
          	switch(data.result)
			{
				case "failed":
					//alert(data.msg);
					break;
				case "update":
					window.location.reload();
					break;
			}
        });
	}
	
	$.basket.update = function() {
		var qtys = $("input[id^=q_]");

		var data = {};
		
		$.each(qtys, function() {
			var e = $(this), k = e.attr('id').split('_').pop();
			var v = e.val().match(/[0-9]+/g);
			data[k] = parseInt(v, 10);
		});
		
		var json = $.toJSON(data);
		var url = script + "?action=update&data=" + json;

		$.getJSON(url, function(data) {
          	switch(data.result) {
				case "failed":
					//alert(data.msg);
					break;
				case "update":
					window.location.reload();
					break;
			}
        });
	}
	
	function objectLength(obj)
	{
		var count = 0;
		if(typeof(obj) != "undefined")$.each(obj,function(){count++;})
		return count;
	}
	
	function updateBasket(data)
	{
		if(data)
		{
			var total = 0;
			for(var item in data)
			{
				total += parseInt(data[item]["qty"]);
			}
			$("#mini_basket").html("basket ("+parseInt(total)+")");
		}
	}

})(jQuery);

/*
 * Customer
 */
(function($) {
	
	$.customers = {};
	
	$.customers.change_country = function(type) {
		
		$("#searching_county_"+type).show();
		$("#display_county_"+type).hide();

		var selected = arguments[1] || '';
		var callback = arguments[2] || null;
		var country_id = $("#country_id_"+type+" :selected").val();
		var url = dbScript + "?action=get&type=counties&id=" + country_id;
		var field;

		$.getJSON(url, function(data)  {
			switch(data.result) {
				case "got":

					if(objectLength(data.data)) {

						field = $('<select>').attr({
							'id': 'county_id_' + type,
							'name': 'county_id_' + type
						});

						// default option
						field.append($('<option>').html('Please Select One').val('0'));

						for(var county in data.data) {
							var opt = $('<option>').html(data.data[county]["county_name"]).val(county);

							if(selected == county) {
								opt.attr('selected', 'selected');
							}
							
							field.append(opt);
						}

						$("#postcode_" + type).show();

					} else {

						field = $('<input>').attr({
							'id': 'county_id_' + type,
							'name': 'county_id_' + type
						}).val(selected);

						$("#postcode_" + type).hide();

					}

					// update field
					$("#display_county_" + type).html(field);

					break;
			}

			// exec callback
			if(typeof callback == 'function') {
				callback();
			}
			
			$("#searching_county_" + type).hide();
			$("#display_county_" + type).show();
		});
	}
	
	$.customers.clear_address = function(type) {
		var fields = ['addressbook_first_name', 'addressbook_last_name', 'addressbook_company', 'addressbook_address1',
			'addressbook_address2', 'addressbook_town', 'addressbook_postcode', 'addressbook_telephone', 'country_id', 'county_id'];

		for(var i = 0; i < fields.length; i += 1) {
			$("#" + fields[i] + "_" + type).val("");
		}
	}
	
	$.customers.same_as_billing = function() {

		var fields = ['addressbook_first_name', 'addressbook_last_name', 'addressbook_company', 'addressbook_address1',
			'addressbook_address2', 'addressbook_town', 'addressbook_postcode', 'addressbook_telephone'];

		for(var i = 0; i < fields.length; i += 1) {
			var field = fields[i];
			$("#" + field + "_shipping").val($("#" + field + "_billing").val());
		}
		
		// copy select box
		$("#country_id_shipping").val($("#country_id_billing :selected").val());

		// update county field
		$.customers.change_country('shipping', $("#county_id_billing").val());
	}
	
	$.customers.show_shipping = function() {
		$.customers.same_as_billing();
		$("#address_same").val("1");
	}

	$.customers.clear = function() {
		$("#customer_id").val(0);				
		$("#display_customer_email").val("");
		$("#customer_group_id").val(1);
		
		$.customers.clear_address("billing");
		$.customers.clear_address("shipping");
	};
	
	$.customers.search = function() {
		$("#searching_customers").show();
		$("#search_results_customers").hide();
		
		var data = {};
		
		if($("#search_customer_id").val())data["customer_id"] = $("#search_customer_id").val();
		if($("#search_customer_first_name").val())data["customer_first_name"] = $("#search_customer_first_name").val();
		if($("#search_customer_last_name").val())data["customer_last_name"] = $("#search_customer_last_name").val();
		if($("#search_billing_name").val())data["billing_name"] = $("#search_billing_name").val();
		if($("#search_customer_company").val())data["customer_company"] = $("#search_customer_company").val();
		if($("#search_customer_email").val())data["customer_email"] = $("#search_customer_email").val();
		if($("#search_postcode").val())data["postcode"] = $("#search_postcode").val();
		if($("#search_customer_group_id :selected").val())data["customer_group"] = $("#search_customer_group_id :selected").val();
		if($("#search_pages_customers :selected").val())data["page"] = $("#search_pages_customers :selected").val();
					
		var json = $.toJSON(data);
		$.getJSON(searchScript+"?type=customers&data="+json,
        function(data)
        {
			$("#searching_customers").hide();
			$("#search_results_customers").show();
			customer = data.data;
			if(objectLength(customer))
			{
				var html = " ";
				for(var element in customer)
				{
					html 	+= 	"<tr id='customer_"+customer[element]["customer_id"]+"'>"
							+	'<td><button class="button">select</button></td>'
							+	"<td>"+customer[element]["customer_first_name"]+"</td>"
							+	"<td>"+customer[element]["customer_last_name"]+"</td>"
							+	"<td>"+customer[element]["customer_email"]+"</td>"
							+	"<td>"+customer[element]["customer_group_title"]
							+	'<script type="text/javascript">$("#customer_'+customer[element]["customer_id"]+'").click(function(){$.customers.select('+element+');});</script>'
							+	"</td></tr>";
				}
				$('#customers_table tbody').html(html);
				
				var pages = "";
				
				for(var iLoop=1;iLoop<=data.pages;iLoop++)
				{
					pages += "<option value='"+iLoop+"'";
					if($("#search_pages_customers :selected").val() == iLoop)pages+= "selected";
					pages += ">"+iLoop+"</option>";
				}
				
				$("#search_pages_customers").html(pages);
			}
			else $("#customers_table").html("No Results");
        });
	};
	
	$.customers.select = function(id) {
		$("#customer_id").val(customer[id]["customer_id"]);				
		$("#display_customer_email").val(customer[id]["customer_email"]);
		$("#customer_group_id").val(customer[id]["customer_group_id"]);
		
		$.customers.set_address("billing", id);
		$.customers.set_address("shipping", id);
			
		$(document).trigger('popup_close');
	};
	
	$.customers.set_address = function(type, id) {

		var fields = ['addressbook_first_name', 'addressbook_last_name', 'addressbook_company', 'addressbook_address1',
			'addressbook_address2', 'addressbook_town', 'addressbook_postcode', 'addressbook_telephone', 'country_id', 'county_id'];

		for(var i = 0; i < fields.length; i += 1) {
			var field = fields[i];
			$("#" + field + "_" + type).val(customer[id][field + "_" + type]);
		}

		$.customers.change_country(type,customer[id]["county_id_"+type]);
	};

})(jQuery);

/*
 * Pagination
 */
(function($) {

	var script = "/scripts/sessionHandler.php";
	var sessionVar = 'pagination';
	var totalResults = 0;
		
	$.pagination = {};
	
	$.pagination.change_page = function(page) {
		//alert(page);
		$.session.update(sessionVar,"page",page,"updatePagination");
	}
	
	$.pagination.clear = function() {
		$.getJSON(dbScript+"?action=delete&type=pagination&id=0", function(data)  {
          	switch(data.result) {
				case "deleted":
					
					break;
				case "deleted":
					//alert(data.msg);
					break;
			}
        });
	}
	
	$.pagination.update = function(total) {
		totalResults = total;
		//alert(script+"?action=get&variable="+sessionVar);
		$.getJSON(script+"?action=get&variable="+sessionVar,
		function(data)
        {
          	switch(data.result)
			{
				case "get_failed":
					//alert(data.msg);
					break;
				case "got":
					updatePaginationHtml(null,data.data);
					break;
			}
        });
	}
	
	$.pagination.setup = function() {
		$('body').bind("updatePagination",function (event,data){updatePagination(event,data)});
	}
	
	function updatePagination(event, data) {
		//alert("update");
		window.location.reload();
	}
	
	function updatePaginationHtml(event, data) {
		if(data) {
			var html = "";
			if(data["page"] != 1)html += '<a href="#page_prev" onclick="$.pagination.change_page('+(parseInt(data["page"])-1)+')">prev</a>&nbsp;|&nbsp;';
			var pages = parseInt(data["pages"])+1;
			for(var iLoop=1;iLoop<pages;iLoop++)
			{
				if(iLoop != parseInt(data["page"]))html+='<a href="#page" onclick="$.pagination.change_page('+iLoop+')">'+iLoop+'</a>';
				else html+=iLoop;
				if(iLoop+1 != pages)html+=",&nbsp;";
			}
			if(data["page"] != pages-1)html += '&nbsp;|&nbsp;<a href="#page_next" onclick="$.pagination.change_page('+(parseInt(data["page"])+1)+')">next</a>';
			//html += data["page"];
			$(".pagination").html(html);
			$("#search_result").html("found "+totalResults+" results");
		}
	}

})(jQuery);

/*
 * Postcode Finder
 */
(function($) {
	var addresses = null;
	var detail = null;
	var script = "/scripts/postcode_finder.php";
	
	$.postcode = {};
	
	$.postcode.change_address = function(select, type) {
		$("#addressbook_address1_"+type).val(addresses[select.value]);
		$("#addressbook_address2_"+type).val("");
		$("#addressbook_town_"+type).val(detail["PostTown"]);
		$("#addressbook_postcode_"+type).val(detail["Postcode"]);

		$("#country_id_"+type).val("1");

		$.customers.change_country(type, detail["county_id"]);
	}
	
	$.postcode.find = function(postcode,type) {
		$("#searching_postcode_"+type).show();
		$.getJSON(script+"?p="+postcode, function(data)  {
          	switch(data.result) {
				case "got":
					var html = "";
					if(data.data.detail)detail = data.data.detail;
					if(data.data.addresses) {
						addresses = data.data.addresses;
						html += "<select onchange='javascript:$.postcode.change_address(this,\""+type+"\");'><option value='-1'>Please Select One</option>";
						for(var postcode in data.data.addresses) {
							html +="<option value='"+postcode+"'>"+truncate(data.data.addresses[postcode],40)+"</option>";
						}
						html += "</select>";
					} else {
						$("#"+type+"_address_table tbody").show();
					}
					$("#addresses_"+type).html(html);
					
					break;
				case "get_failed":
					//alert(data.msg);
					break;
			}
          	$("#searching_postcode_"+type).hide();
        });
	}
	
})(jQuery);



/*
 * jQuery JSON Plugin
 * version: 1.0 (2008-04-17)
 */
(function($) {
    function toIntegersAtLease(n)
    // Format integers to have at least two digits.
    {
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date)
    // Yes, it polutes the Date namespace, but we'll allow it here, as
    // it's damned usefull.
    {
        return this.getUTCFullYear()   + '-' +
             toIntegersAtLease(this.getUTCMonth()) + '-' +
             toIntegersAtLease(this.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        }

    $.quoteString = function(string)
    // Places quotes around a string, inteligently.
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
    {
        if (escapeable.test(string))
        {
            return '"' + string.replace(escapeable, function (a)
            {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"'
        }
        return '"' + string + '"';
    }

    $.toJSON = function(o, compact)
    {
        var type = typeof(o);

        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";

        // Is it a string?
        if (type == "string")
        {
            return $.quoteString(o);
        }

        // Does it have a .toJSON function?
        if (type == "object" && typeof o.toJSON == "function")
            return o.toJSON(compact);

        // Is it an array?
        if (type != "function" && typeof(o.length) == "number")
        {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push( $.toJSON(o[i], compact) );
            }
            if (compact)
                return "[" + ret.join(",") + "]";
            else
                return "[" + ret.join(", ") + "]";
        }

        // If it's a function, we have to warn somebody!
        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }

        // It's probably an object, then.
        ret = [];
        for (var k in o) {
            var name;
            var type = typeof(k);

            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys

            val = $.toJSON(o[k], compact);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }

            if (compact)
                ret.push(name + ":" + val);
            else
                ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    }

    $.compactJSON = function(o)
    {
        return $.toJSON(o, true);
    }

    $.evalJSON = function(src)
    // Evals JSON that we know to be safe.
    {
        return eval("(" + src + ")");
    }

    $.secureEvalJSON = function(src)
    // Evals JSON in a way that is *more* secure.
    {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    }
})(jQuery);
