/**
 * Global Delivery.com callback functions. Requires jQuery
 *
 * jslint white: true, browser: true, devel: true, on: true, onevar: true, undef: true, nomen: true,
 *  eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true
 *  
 * "use strict";
 */
function sModal_close(keep_hash) {
	
	//If there is already an open smodal, don't do anything
	if(!document.getElementById('smodal_close')) {
		return;
	}
    if (document.body.firstChild.className !== "container_12" && document.body.firstChild.className !== "container") {
        if (document.body.childNodes.item(0)) {
            var current_element = document.body.childNodes.item(0);
            while (current_element.className !== "container_12" && current_element.className !== "container") {
                document.body.removeChild(current_element);
                current_element = document.body.childNodes.item(0);
            }
        }
    }
//    if (document.location.hash.substr(document.location.hash.length-6 , 6) == 'sModal') {
	if(keep_hash !== true){
		document.location.hash = "#!";
	}
//    }    
}

var sModal = {
	resetHash:  0,
	onClose: null,
    close: function () {
        if (document.body.childNodes[0].className.indexOf("sModal") > -1) {
        	document.body.removeChild(document.body.childNodes[2]);
        	document.body.removeChild(document.body.childNodes[1]);
        	document.body.removeChild(document.body.childNodes[0]);
        }
        if (sModal.onClose != null) {
        	sModal.onClose();
        }
        sModal_close();
    },
    create: function (width) {
        var newBg, sMode, newClose;
        newBg = document.createElement("div");
        newBg.className = "ajax_gray_bg";
    
        if (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null) {
        	newBg.style.height = '1944px';
        	newBg.style.width  = '1944px'; 
        }
        
        document.body.insertBefore(newBg, document.body.childNodes[0]);

        sMode = document.createElement("div");
        sMode.className = "sModal";
        sMode.id='sModal_popup';        
        sMode.style.display = 'none';

        newClose = document.createElement("img");
        newClose.src = "/images/button-modal-close.gif";
        newClose.onclick = sModal.close;
        newClose.className = "sModal close";
        newClose.id = "smodal_close";
        newClose.style.display = 'none';
		
        document.body.insertBefore(sMode, document.body.childNodes[0]);
        document.body.insertBefore(newClose, document.body.childNodes[1]);

//        if (document.location.hash.substr(document.location.hash.length-6 , 6) == 'sModal') {
//        	document.location.hash = document.location.hash.substr(0, document.location.hash.length-6);
//        }
//        document.location.hash += 'sModal';

        document.body.style.cursor = 'wait';
        sModal.resize();
		if (parseInt(width, 10) > 0) {
            sModal.resize(width);
		}
//        sModal.watch_hash();
    },
    populate: function (html, padding) {
        var modalNode = document.body.childNodes[0];
        if (modalNode.className === "sModal") {
            if (padding !== undefined) {
                modalNode.style.padding = padding + "px";
                if (/MSIE 6/i.test(navigator.userAgent) ||
                    /MSIE 7/i.test(navigator.userAgent)
				) {
					//modalNode.style.paddingRight = 20 + padding + "px";
                }
            }
            modalNode.innerHTML = html;
            modalNode.style.display = '';
            document.body.childNodes[2].style.display = '';
            document.body.childNodes[1].style.display = '';
            if (modalNode.getElementsByTagName('form').length > 0) {
                var modalForm = modalNode.getElementsByTagName('form').item(0),
                    focus_is_set = false,
                    i = 0;
                while (focus_is_set === false && i < modalForm.elements.length) {
                    if (modalForm.elements[i].type !== 'hidden') {
                        modalForm.elements[i].focus();
                        focus_is_set = true;
                    }
                    i++;
                }
            }
            sModal.resize();
            document.body.style.cursor = '';
        }
    },
    resize: function (width) {
		var isIE6 = /MSIE 6/i.test(navigator.userAgent),
			isIE7 = /MSIE 7/i.test(navigator.userAgent);

		if (!document.body.childNodes[1].style) {
            document.body.childNodes[1].setAttribute('style', '');  //Especially for IE
        }
        if (window.innerHeight) {
            document.body.childNodes[0].style.top = (window.innerHeight - document.body.childNodes[0].clientHeight) / 2 + "px";
            document.body.childNodes[1].style.top = (((window.innerHeight - document.body.childNodes[0].clientHeight) / 2) - 30) + "px";
            document.body.childNodes[0].style.left = (document.body.clientWidth - document.body.childNodes[0].clientWidth) / 2 + "px";
            document.body.childNodes[1].style.left = (((document.body.clientWidth + document.body.childNodes[0].clientWidth) / 2) - 18) + "px";
        } else if (isIE6) {			// IE 6
            document.body.childNodes[0].style.top = "47px";
            document.body.childNodes[1].style.top = "30px";
            document.body.childNodes[0].style.left = (document.body.clientWidth - document.body.childNodes[0].clientWidth) / 2 + "px";
            document.body.childNodes[1].style.left = (((document.body.clientWidth + document.body.childNodes[0].clientWidth) / 2) - 9) + "px";
            scroll(0, 0);
        } else {					// IE 7, 8
            document.body.childNodes[0].style.top = (document.documentElement.clientHeight - document.body.childNodes[0].clientHeight) / 2 + "px";
            document.body.childNodes[1].style.top = (((document.documentElement.clientHeight - document.body.childNodes[0].clientHeight) / 2) - 30) + "px";
            document.body.childNodes[0].style.left = (document.body.clientWidth - document.body.childNodes[0].clientWidth) / 2 + "px";
            if (isIE7) {
                document.body.childNodes[1].style.left = (((document.body.clientWidth + document.body.childNodes[0].clientWidth) / 2) - 9) + "px";
            }
            else {
                document.body.childNodes[1].style.left = (((document.body.clientWidth + document.body.childNodes[0].clientWidth) / 2) - 18) + "px";
            }
        }
        if (parseInt(document.body.childNodes[0].style.top, 10) < 20) {
            document.body.childNodes[0].style.top = "20px";
        }
        if (parseInt(document.body.childNodes[1].style.top, 10) < -10) {
            document.body.childNodes[1].style.top = "-10px";
        }
        if (width) {
        	document.body.childNodes[0].style.width = width+"px";
        }

		//make sure the modal is not too long to fit on smaller screens
       	var browserHeight = $(window).height();
		//alert(browserHeight+'X'+$('#sModal_popup').height());
		if(browserHeight < $('#sModal_popup').height() + 50){
			if (navigator.userAgent.match(/iPad/i) == null || navigator.userAgent.match(/iPhone/i) == null) {
				$('#sModal_popup').height((browserHeight - 50)+'px'); //this fixes issues related to crappy resolutions
			}
		}        
        
    }
//    watch_hash: function () {
//    	if (sModal.resetHash == 1) {
//    		document.location.hash += 'sModal';
//    		sModal.resetHash = 0;
//    	}
//        if (document.location.hash.substr(document.location.hash.length-6 , 6) == 'sModal') {
//        	var t = setTimeout("sModal.watch_hash()", 200);	//string implies an eval. Can we force this to a function?
//        } else {
//            clearTimeout("sModal.watch_hash()");
//            sModal_close();
//        }
//    }
};

var jHashOriginalContent = '';
var jLastHash = '';

function jHash(funcCall) {
	var args_array = [];
	args_array[0] = funcCall;
	var passthrough_arguments = arguments; // the current arguments variable will be lost as soon as the scope changes
	for (var i = 1; i < passthrough_arguments.length; i++) {
		args_array[i] =  typeof(passthrough_arguments[i]) == "string" ?
			escape(encodeURIComponent("'"+passthrough_arguments[i].replace(/'/g,"\'")+"'")) :
			escape(encodeURIComponent(passthrough_arguments[i].toString()));
	}
	// window.location.href = window.location.protocol + "//" + window.location.hostname + window.location.pathname + "#jHash" + args_a
	// ]'
	// rray.join("|");
	
	if(window.location.hash == ("#jHash" + unescape(args_array.join("|")))) {
		runJHash(location.hash.substr(6));
	}
	else {
		window.location.hash = "#jHash" + args_array.join("|");
	}
}

function runJHash(funcArgs) {
	args_array = funcArgs.split("|");
	js_string = args_array[0] + "(";
	args_array.shift();
	for(i=0;i<args_array.length;i++) {
		args_array[i] = decodeURIComponent(args_array[i]);
	}
	js_string += args_array.join(",") + ")";
	eval(unescape(js_string));
}

$(document).ready(function() {
	jHashOriginalContent = document.body.innerHTML;

	setInterval(jHashIntervalFunction, 250);
});

function jHashIntervalFunction() {
	if(jLastHash != window.location.hash) {
		if(location.hash == "#!") {
			sModal_close();
		}
		else if(location.hash.substr(1,5) == "jHash") {
			runJHash(location.hash.substr(6));
		}
		else if(location.hash == "") {
			document.body.innerHTML = jHashOriginalContent;
		}
	}

	jLastHash = window.location.hash;
}

/*
var jLastHash = '';
var jHashOriginalContent = {};

function jHash(funcCall) {
	var args = {};
	if(window.location.hash.substr(0,3) == '#!!') {
		args = $.unserialize(window.location.hash.substr(3));
	}
	args = args == null ? {} : args;
	
//	var jHashPrefix = 0;
//	for (arg in args) {
//		jHashPrefix++;
//	}
//	if (jHashPrefix < 1) {
//		jHashPrefix = "000";
//	}
//	else if (jHashPrefix < 10) {
//		jHashPrefix = "00" + jHashPrefix;
//	}
//	else if (jHashPrefix < 100) {
//		jHashPrefix = "0" + jHashPrefix;
//	}

	
	var passthrough_arguments = arguments; // the current arguments variable will be lost as soon as the scope changes
	for (var i = 1; i < passthrough_arguments.length; i++) {
		passthrough_arguments[i] = typeof(passthrough_arguments[i]) == "string" ?
			("'"+passthrough_arguments[i].replace(/'/g,"\'")+"'") :
			passthrough_arguments[i].toString();
	}
	var pta = Array.apply(null, passthrough_arguments);
	pta.shift();
	
	if (typeof(args[funcCall]) != "undefined") {
		delete args[funcCall];
	}
	
	var argKeys = new Array();
	var argValues = new Array();
	argKeys.push(funcCall);
	argValues.push(encodeURIComponent(pta));
	for (arg in args) {
		argKeys.push(arg);
		argValues.push(args[arg].replace("%25", "%2525"));
	}
	
	var newArgs = new Object();
	args[funcCall] = encodeURIComponent(pta);
	
	hashFix = "";
	for (i in argKeys) {
		hashFix += argKeys[i]+"="+argValues[i]+"&";
	}
	hashFix = hashFix.substring(0, hashFix.length-1);
	
	var newHash = encodeURI('!!'+$.param(args));
	var newnewHash = encodeURI('!!'+hashFix);
	
	//if we have no hash, remember this page state before we do anything
	if(jLastHash == '' && window.location.hash == '') {
		jHashOriginalContent[''] = document.body.innerHTML;
	}
	window.location.hash = newnewHash;
	jHashIntervalFunction();
}

$(document).ajaxComplete(function() {
	jHashOriginalContent[window.location.hash] = document.body.innerHTML;
});

setInterval(jHashIntervalFunction, 500);
function jHashIntervalFunction() {
if(jLastHash != window.location.hash && document.location.hash.substr(document.location.hash.length-6 , 6) != 'sModal') {
	//store or restore content based on hash 
	if(jHashOriginalContent[window.location.hash]) {
		document.body.innerHTML = jHashOriginalContent[window.location.hash];
		if (document.getElementById('smodal_close') != null) {
			document.getElementById('smodal_close').onclick = sModal.close;
		}
	} else {
		if(window.location.hash.substr(0,3) == '#!!') {
			var args = decodeURIComponent(window.location.hash.substr(3));
		}	
		
		if(args != null) {
			$.each($.unserialize(args), function(key,val) {
				//run the function
//				alert(jLastHash);
//				alert(window.location.hash);
				eval(decodeURIComponent(key)+"("+decodeURIComponent(val)+");");
			});
		}
	}
	
	jLastHash = window.location.hash;
}
} */
/**
* $.unserialize
*
* Takes a string in format "param1=value1&param2=value2" and returns an object { param1: 'value1', param2: 'value2' }. If the "param1" ends with "[]" the param is treated as an array.
*
* Example:
*
* Input: param1=value1&param2=value2
* Return: { param1 : value1, param2: value2 }
*
* Input: param1[]=value1&param1[]=value2
* Return: { param1: [ value1, value2 ] }
*
* @todo Support params like "param1[name]=value1" (should return { param1: { name: value1 } })
*/

/*
(function($){
	$.unserialize = function(serializedString){
		var str = decodeURI(serializedString);
		var pairs = str.split('&');
		var obj = {}, p, idx, val;
		for (var i=0, n=pairs.length; i < n; i++) {
			p = pairs[i].split('=');
			idx = p[0];

			if (idx.indexOf("[]") == (idx.length - 2)) {
//				Eh um vetor
				var ind = idx.substring(0, idx.length-2)
				if (obj[ind] === undefined) {
					obj[ind] = [];
				}
				obj[ind].push(p[1]);
			}
			else {
				obj[idx] = p[1];
			}
		}
		return obj;
	};
})(jQuery); */











//this code in copied somewhere from the internet...
/**
 * jQuery hashchange 1.0.0
 *
 * (based on jquery.history)
 *
 * Copyright (c) 2008 Chris Leishman (chrisleishman.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */
(function($) {

$.fn.extend({
    hashchange: function(callback) { this.bind('hashchange', callback) },
    openOnClick: function(href) {
		if (href === undefined || href.length == 0)
			href = '#';
		return this.click(function(ev) {
			if (href && href.charAt(0) == '#') {
				// execute load in separate call stack
				window.setTimeout(function() { $.locationHash(href) }, 0);
			} else {
				window.location(href);
			}
			ev.stopPropagation();
			return false;
		});
    }
});

// IE 8 introduces the hashchange event natively - so nothing more to do
if ($.browser.msie && document.documentMode && document.documentMode >= 8) {
	$.extend({
		locationHash: function(hash) {
	        if (!hash) hash = '#';
	        else if (hash.charAt(0) != '#') hash = '#' + hash;
	        location.hash = hash;
	    }
	});
	return;
}

var curHash;
// hidden iframe for IE (earlier than 8)
var iframe;

$.extend({
	locationHash: function(hash) {
		if (curHash === undefined) return;

		if (!hash) hash = '#';
		else if (hash.charAt(0) != '#') hash = '#' + hash;

		location.hash = hash;

		if (curHash == hash) return;
		curHash = hash;

		if ($.browser.msie) updateIEFrame(hash);
		$.event.trigger('hashchange');
	}
});

$(document).ready(function() {
    curHash = location.hash;
    if ($.browser.msie) {
        // stop the callback firing twice during init if no hash present
        if (curHash == '') curHash = '#';
        // add hidden iframe for IE
        iframe = $('<iframe />').hide().get(0);
        $('body').prepend(iframe);
        updateIEFrame(location.hash);
        setInterval(checkHashIE, 100);
    } else {
        setInterval(checkHash, 100);
    }
});
$(window).unload(function() { iframe = null });

function checkHash() {
    var hash = location.hash;
    if (hash != curHash) {
        curHash = hash;
        $.event.trigger('hashchange');
    }
}

if ($.browser.msie) {
    // Attach a live handler for any anchor links
    $('a[href^=#]').live('click', function() {
        var hash = $(this).attr('href');
        // Don't intercept the click if there is an existing anchor on the page
        // that matches this hash
        if ($(hash).length == 0 && $('a[name='+hash.slice(1)+']').length == 0) {
            $.locationHash(hash);
            return false;
        }
    });
}

function checkHashIE() {
    // On IE, check for location.hash of iframe
    var idoc = iframe.contentDocument || iframe.contentWindow.document;
    var hash = idoc.location.hash;
    if (hash == '') hash = '#';

    if (hash != curHash) {
        if (location.hash != hash) location.hash = hash;
        curHash = hash;
        $.event.trigger('hashchange');
    }
}

function updateIEFrame(hash) {
    if (hash == '#') hash = '';
    var idoc = iframe.contentWindow.document;
    idoc.open();
    idoc.close();
    if (idoc.location.hash != hash) idoc.location.hash = hash;
}

})(jQuery);

//handles what happens after change the time (reload cart, search results, or catalog content based on what page we are on)
function time_updated(response) {
	if($(".merchant_page_content").length > 0) {
		reload_catalog_page();
	}
	if($("#results").length > 0) {
		reload_search_page();
	}
}

//Change order type (PICKUP|DELIVERY)
function update_pickup_type(selector) {
	document.body.style.cursor = 'wait';
	
	var order_type_selection = document.getElementById('order_type_selection').value;
	if(order_type_selection == 'PICKUP'){
		$('#start_group_order').hide();
	} else {
		$('#start_group_order').show();
	}
	
	$.post(window.location.pathname, { ajax_submit: 1, Xhv_sot: selector.value }, function(data) 
	{
		var jsResult = jQuery.parseJSON(data);
		
		$('.full_cart_header').html(jsResult.full_cart_header);
		$('.full_cart_content').html(jsResult.cart_body);
		
		//Update the mini cart's checkout button
		button_href = $('.full_cart_content .button a').attr('href');		
		$('.cart_summary div a').attr('href', button_href);
		
		document.body.style.cursor = 'default';
	});
}
