// JavaScript Document
function scrollTo(selector) {
	var targetOffset = $(selector).offset().top;
	$('html,body').animate({scrollTop: targetOffset}, 500);
}

function sizeIFrame(idNum) 
{
	var helpFrame = $("#onewp_mapFrame_" + idNum);
	var innerDoc = (helpFrame.get(0).contentDocument) ? helpFrame.get(0).contentDocument : helpFrame.get(0).contentWindow.document;
	helpFrame.height(innerDoc.body.scrollHeight + 100);
}

	function ieCleanURL(url)
	{
		if(!url)
			return false;
	
		var tmpURL2 = '';
		tmpURL2 = url.replace(document.domain, '');
		tmpURL2 = tmpURL2.replace(/http:\/\//, '');
		var tmpURL = tmpURL2.split('/');
		var tmpLen = tmpURL.length;
		if(tmpLen == 2)
			tmpURL2 = tmpURL[1];
		return tmpURL2;
	}
/*
	function createGallery(photoset, idNum, height)
	{
		if(!height)
			height = 300;
		$('#onewp_flickr_' + idNum).empty();
		
		//block();
		$.post('/widgets/getFlickrGalleryImages', { gallery: photoset, divID: idNum }, function(data)
		//$.post('/getFlickrGallery.php',{ gallery: photoset, divID: idNum }, function(data)
		{
			$("#onewp_flickr_" + idNum).html(data);
			$("#onewp_photoGal" + idNum).jcarousel();
			$(".jcarousel-prev, .jcarousel-next").click(function() { return false; });
		});
	}
*/
/*
$(".onewp_galImageLink").die('click');
$(".onewp_galImageLink").live('click', function()
{
	$(this).closest('.flickrGalleryMainPhoto').find('img').attr('src', $(this).attr('href'));
	return false;
});
*/
function initFlickr()
{
	/*
	$("div[id*='onewp_flickr_']").each(function(i)
	{
		var id = $(this).attr('id');
		alert(id);
		id = id.replace('onewp_flickr_', '');
		var photoset = $("#onewp_flickr_" + id).attr('class');
		$(this).empty();
		if(photoset != '')
		{
			createGallery(photoset, id);
		}
		else
			createGallery('all', id);
	});
	*/
}

function createGallery(photoset, idNum, height)
{
	if(!height)
		height = 300;
	$('#onewp_flickr_' + idNum).empty();
	
	//block();
	$.post('/widgets/getFlickrGalleryImages', { gallery: photoset, divID: idNum }, function(data)
	//$.post('/getFlickrGallery.php',{ gallery: photoset, divID: idNum }, function(data)
	{
		$("#onewp_flickr_" + idNum).html(data);
		$("#onewp_photoGal" + idNum).jcarousel();
		$(".jcarousel-prev, .jcarousel-next").click(function() { return false; });
	});
}

		
		function initRss()
		{
			$("div[id*='onewp_rss_']").each(function(i)
			{
				var id = $(this).attr("id");
				id = id.replace("onewp_rss_", "");
				optS = $(this).parent().parent().children(".onewp_options").text();
				//$(this).empty();
				//alert(optS + "test");
				$.post("/getRSS.php", { opts: optS}, function(data)
				{
					$("#onewp_rss_" + id).html(data);
				});
				
			});
		}

		function initUserForms()
		{
			//alert('test');
			$(".onewp_userform").submit( function ()
			{
				//alert('test');
				var myForm = $(this);
				var fID = $(this).attr("id");
				$.ajax( 
				{
					type: "POST", 
					url: "/userFormSubmit.php",
					data: $(this).serialize(),
					success: function (data)
					{
						myForm.before('<div style="padding: 5px; border: 1px solid #F00; font-weight: bold; color: #F00; font-size: 14px;" id="formSubmit_' + fID + '"></div>');
						$("#formSubmit_" + fID).html(data);
						//initPages();
					}
				});
				return false;
			});
		}
		
		function initCartLinks()
		{
			$("#viewCartButton").unbind('click');
			$("#viewCartButton").click(function()
			{
				//alert('test');
				$.post('/getCartOverview.php', {}, function(data)
				//$.post('/simpleCart/simpleCartConfig/getCartOverview', {}, function(data)
				{
					$("#fullCart").html(data);
					scrollTo('#fullCart');
					initCartLinks();
				});
				return false;
			});
			
			$(".simpleCartAddToCart").unbind("click");
			$(".simpleCartAddToCart").click(function(i)
			//$(".simpleCartAddToCart").live('click', function(i)
			{
				//alert('test');
				//var sVals = new Array;
				//$("#fullCart").find("select :selected").each(function(k)
				//{
				//	sVals[$(this).atrr('id')] = $(this).val();
				//});
				//sVals = serialize(sVals);
				
				var optArr = new Array;
				$(".simpleCartOptionSelect").each(function(i)
				{
					var optName = $(this).closest('.simpleCartOption').find('.simpleCartOptionTitle').text();
					optArr[optName] = $(this).val();
				});
				optArr = serialize(optArr);
				
				$.post('/getCartItemList.php', { id: ieCleanURL($(this).attr("href")), opts: optArr, add: 1 }, function(data)
				//$.post('/simpleCart/simpleCartConfig/index', { id: ieCleanURL($(this).attr("href")), add: 1 }, function(data)
				{
					$("#fullCart").html(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
			
			$(".simpleCartGetItemDetail").unbind('click');
			$(".simpleCartGetItemDetail").click(function()
			{
				//alert($(this).parent(".onewp_cart").attr('id'));
				$.post('/getCartItem.php', { id: ieCleanURL($(this).attr("href")) }, function(data)
				//$.post('/simpleCart/simpleCartConfig/getCartItem', { id: ieCleanURL($(this).attr("href")) }, function(data)
				{
					
					$("#fullCart").html(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
			
			$(".backToCartList").unbind('click');
			$(".backToCartList").click(function()
			{
				$.post('/getCartItemList.php', { userID: ieCleanURL($(this).attr('href')) }, function(data)
				//$.post('/simpleCart/simpleCartConfig/index', { userID: ieCleanURL($(this).attr('href')) }, function(data)
				{
					$("#fullCart").html(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
			
			$(".backToCartCategories").unbind('click');
			$(".backToCartCategories").click(function()
			{
				$.post('/getCart.php', { userID: ieCleanURL($(this).attr('href')) }, function(data)
				//$.post('/simpleCart/simpleCartConfig/index', { userID: ieCleanURL($(this).attr('href')) }, function(data)
				{
					$("#fullCart").replaceWith(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
			
			$(".clearCart").unbind('click');
			$(".clearCart").click(function()
			{
				$.post('/getCartItemList.php', { userID: ieCleanURL($(this).attr('href')), clearCart: 1 }, function(data)
				//$.post('/simpleCart/simpleCartConfig/index', { userID: ieCleanURL($(this).attr('href')), clearCart: 1 }, function(data)
				{
					$("#fullCart").html(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
				
			$(".simpleCartRemoveItem").unbind('click');
			$(".simpleCartRemoveItem").click(function()
		 	//$(".updateCartItemNum").live('click', function()
			{
				var tmp = ieCleanURL($(this).attr('href'));
				tmp = tmp.split('|');
				
				//$.post('/getCartItemList.php', { userID: tmp, remove: 1, id: tmp[0], cartItem: tmp[1] }, function(data)
				$.post('/getCartOverview.php', { userID: tmp, remove: 1, id: tmp[0], cartItem: tmp[1] }, function(data)
				//$.post('/simpleCart/SimpleCartConfig/index', { userID: tmp, newItemNum: $('#cart_amt_' + tmp).val(), id: tmp }, function(data)
				{
					$("#fullCart").html(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
			
			$(".updateCartItemNum").unbind('click');
			$(".updateCartItemNum").click(function()
		 	//$(".updateCartItemNum").live('click', function()
			{
				var tmp = ieCleanURL($(this).attr('href'));
				$.post('/getCartItemList.php', { userID: tmp, newItemNum: $('#cart_amt_' + tmp).val(), id: tmp }, function(data)
				//$.post('/simpleCart/SimpleCartConfig/index', { userID: tmp, newItemNum: $('#cart_amt_' + tmp).val(), id: tmp }, function(data)
				{
					$("#fullCart").html(data);
					initCartLinks();
					scrollTo('#fullCart');
				});
				return false;
			});
		}
			

		$(document).ready(function() 
		{
			$("img[id^=onewp_img_], #onewp_headerImg").resizable('destroy');
			
			
			
			initFlickr();
			initUserForms();
			//initGoogleMaps();
			initRss();
			initCartLinks();
			
			$("div[id^=onewp_item_]").each(function(i)
			{
				var idNum = $(this).attr('id');
				var idRE = /onewp_item_(.*)/;
				idNum = idNum.replace(idRE,"$1");
				//alert(idNum);
		
				var jsonOpts = $.secureEvalJSON($("#onewp_item_" + idNum).children('.onewp_options').text());
				var tmpOpts = new Object;
				var wType = '';
				
				$.each(jsonOpts, function(i, val)
				{
					if(jsonOpts[i]['name'] == 'wType')
					{
						wType = jsonOpts[i]['value'];
					}
				});
				if(wType === 'flickr_gallery')
					eval(wType + 'InitPageItem("' + idNum + '");');
				//alert(wType + 'InitPageItem(' + idNum + ');');
			});	
			//$(document).pngFix(); 
			//var cartStr = $(".onewp_cart").parent().parent().children('.onewp_options').text();
			//$.post('/getCartItemList.php', { optS: cartStr }, function(data)
			//$.post('/simpleCart/simpleCartConfig/index', { optS: cartStr }, function(data)
			//{
			//	$(".onewp_cart").html(data);
			//	initCartLinks();
			//	$(document).pngFix(); 
			//});
			
	
		});
			
function serialize( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;

    }
    if (type != "object" && type != "array") val += ";";
    return val;
}
