/**
 * @copyright    2008 Delivery.com JJ
 * @fileOverview other.js
 * @description  Shared javascript functions
 *
 * jslint white: true, browser: true, undef: true, devel: true, on: true, onevar: true, undef: true, nomen: true,
 *  eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true
 * global $: false, console: false, document: false, sModal: false, window: false
 */
//"use strict"; //May break future javascript

var currentTabs = {};   //new Object(), JSON syntax


/**
 * @function checkAddressInput
 * @param    formId
 * @param    locationSelectorId
 * @param    doSubmit
 * @return   boolean
 */
function checkAddressInput(formId, locationSelectorId, doSubmit) {
	var address = $('#j_address_street_input' + locationSelectorId).val();
	//zip = $('#j_address_zip_input' + locationSelectorId).val();
	document.getElementById('j_address_street_input' + locationSelectorId).value = address;
	//document.getElementById('j_address_zip_input' + locationSelectorId).value = zip;

	if (address === 'Street Address' /*|| zip === 'Zip'*/) {

		sModal.create();
		sModal.populate('<img src="/images/logo.gif" alt="Delivery.com logo"/><p>Please input your address and zip code.</p>');
		return false;
	} else {
		document.body.style.cursor = 'wait';
		$('#j_address_street_input' + locationSelectorId).css('cursor', 'wait');
//		$.post('/search.php', $('#' + formId).serialize() + "&do_ajax=true", function (data) {
		$.post(window.location, $('#' + formId).serialize() + "&do_ajax=true", function (data) {
			if (data.charAt(0) === '{') {
            	
                try {
                    data = jQuery.parseJSON(data);
                } catch (ex) {
                    if (typeof(console) === 'object') {
                        console.warn('checkAddressInput: ' + ex);
                    }
                }

				if(data.content === 'Success') {
		            if (doSubmit === true) {
//						$('#DC_location_id'+locationSelectorId).val('');
						document.getElementById(formId).submit();
			        } else {
			        	$.post(document.getElementById(formId).action, $('#' + formId).serialize() + "&cancel_redirect=true", function (data) {
			                try {
			                    data = jQuery.parseJSON(data);
			                } catch (ex) {
			                    if (typeof(console) === 'object') {
			                        console.warn('checkAddressInput: ' + ex);
			                    }
			                }

			        		sModal.populate(data.content);
			        	});
			        }

	                return true;
				} else {
					sModal_close(true);
					if(document.getElementById('sModal_popup') == null){
						sModal.create();
					}
	                sModal.populate('<img src="/images/logo.gif" alt="Delivery.com logo"/><p>' + data.content + '</p>');
				}
            } //else
            document.body.style.cursor = 'default';
            $('#j_address_street_input' + locationSelectorId).css('cursor', '');
            return false;
        });
	} //end else
	return false;
}

function jAddressBlur(thisObj, event, addressText) {
	console.warn(thisObj);
	console.warn(addressText);
	switch(event) {
		case 'blur':
			thisObj.value = thisObj.value=='' ? addressText : thisObj.value;
			break;
		case 'focus':
			if(thisObj.value==addressText) {
				thisObj.select();
			}
			//thisObj.value = thisObj.value==addressText ? '' : thisObj.value;
			break;
	}
}

function jAddressHover(thisEvent, thisObj) {
	if (thisEvent === 'out') {
		thisObj.style.backgroundColor = '';
	} else {
		thisObj.style.backgroundColor = '#3482bd';
	}
}

/**
 * Location picker for Delivery.com search bar
 *
 * @param formId
 * @param ourId
 * @param thisObj
 * @param loc_street
 * @param loc_zip
 * @param location_id
 */
function jAddressSelect(formId, ourId, thisObj, loc_text, location_id) {
	document.getElementById('DC_location_id' + ourId).value = location_id;
	document.getElementById('j_address_street_input' + ourId).value = loc_text;
	//document.getElementById('j_address_zip_input' + ourId).value = loc_zip;
	var sel = document.getElementById('selAddr');
	if (sel) {
		if (sel.className === '1') {
			sel.id = '';
		} else {
			sel.id = 'alt';
		}
	}
	thisObj.id = 'selAddr';
	thisObj.style.cursor = 'wait';
	return checkAddressInput(formId, ourId, true);
}

/**
 * @function jGetWidth
 * @param    obj
 * @return   int
 */
function jGetWidth(obj) {
	var opera = window.opera ? true : false;
	if (!opera) {
		if (!obj) {
            if (typeof console === 'object') {  //undefined on old IE
                console.warn('jGetWidth has no width for ' + obj);
            }
		}
		return obj.offsetWidth;
	} else {
		return obj.clientWidth ? obj.clientWidth : obj.offsetWidth;
	}
}

/**
 * @function    jAddressPop
 * @param       ourId
 * @param		forceHide
 * @description Location picker
 *
 * @requires    jGetWidth
 */
function jAddressPop(ourId, forceHide) {
	var selPos,
		box = document.getElementById('j_address_street_input' + ourId),
		pop = document.getElementById('j_address_pop' + ourId),
		streetAd = document.getElementById('j_address_street_input' + ourId);

	if (pop && pop.style.display === 'block') {
		if (pop) {
			pop.style.display = '';
			pop.style.left = '';
			pop.style.top = '';
		}
		//jslint: Unexpected use of '^'
	} else if (!forceHide && ((!pop) ^ (pop && pop.style.display !== 'block'))) {
		if (pop) {
			//jAddressBlur(box, 'blur', box.value); //remove focus from the box, causing the current address to repopulate
			pop.style.left = (box.offsetLeft - 1) + "px";
			pop.style.top = (box.offsetTop + 34) + "px";
			pop.style.width = jGetWidth(streetAd) + "px";
			pop.style.display = 'block';
			pop.style.zIndex = 9999;

			selPos = document.getElementById('selAddr');
			if (selPos) {
				pop.scrollTop = (selPos.offsetTop - pop.offsetTop);
			}
		} 
	}
}

/**
 * @function jlHoursHide stolen from global.js
 */
function jlHoursHide() {
	var i,
		thisDiv,
		allDivs = document.getElementsByTagName('div');

	for (i = 0; i < allDivs.length; i++) {
		thisDiv = allDivs[i];
		if (thisDiv.className === 'schedule_hours') {
			thisDiv.style.visibility = 'hidden';
		}
	}
}

/** @todo thisObj is ununused */
function jlHoursShow(thisObj, ourId) {
	jlHoursHide();
	var ourSched = document.getElementById(ourId);
	ourSched.style.visibility = 'visible';
}

function showDate(date, options, num) {
	for (var i = 0; i < options.length; i++) {
		if (options[i].value) {
			document.getElementById('orderTimeTime_' + num + '_' + options[i].value).style.display = 'none';
		}
	}
	var val = document.getElementById('orderTimeTime_' + num + '_' + date);
	//val = document.getElementsByName('orderTimeTime_' + num + '_' + date);
	if (val) {
		val.style.display = 'inline';
	}
}

function showDebugBoxes() {
	if (document.getElementById('tab_box') !== null) {
		document.getElementById('tab_box').style.display = 'block';
    }
	if (document.getElementById('param_box') !== null) {
		document.getElementById('param_box').style.display = 'inline';
    }
	if (document.getElementById('sql_box') !== null) {
		document.getElementById('sql_box').style.display = 'inline';
    }
	if (document.getElementById('var_box') !== null) {
		document.getElementById('var_box').style.display = 'inline';
    }

	//show testing debug info
	var i,
		alldivs = document.getElementsByTagName('div');

	for (i = 0; i < alldivs.length; i++) {
		if (alldivs[i].className === 'testing_debug') {
            alldivs[i].className = 'testing_debug_on';
		}
	}

	var container12 = document.getElementById('container_12');
	if (container12) {
		container12.style.backgroundImage = 'url("/images/thegrid.png")';
    }
}

function showHideVendorSelect() {
	var vendor_select = document.getElementById('vs_bottom_box');
	if (vendor_select.className == 'vs_bottom') {
		vendor_select.className = 'vs_bottom_open';
	} else {
		vendor_select.className = 'vs_bottom';
	} 

	if (typeof retrieve_current_query === 'function') { //TODO where is retrieve_current_query defined?
		retrieve_current_query('c_q');
    }
}

/**
 * Display progress bar
 *
 * @param throbId Jquery syntax, ex:"#loading". Throbber appears after this element
 * @param formId  Jquery syntax. If not null, submits that form
 * @augments jQuery
 */
function submitFormData(formId) {
	//jQuery .html()'s known memory leak will be cleaned by page reload
	document.body.style.cursor = 'wait';
	if (null !== formId) {
		$(formId).submit();
	}
}

/**
 * Display progress bar on submit
 *
 * @param throbId Jquery syntax, ex:"#loading". Throbber appears after this element
 * @param formId  Jquery syntax. If not null, submits that form
 * @param e  event key
 * @augments jQuery, throbber()
 */
function throbKey(throbId, formId, e) {
	if(e.keyCode === 13){
		throbber(throbId, formId);
	}
}

function swapTabs(tabId, boxId, content_function, params) {
	var ct,
		currentTab = currentTabs[boxId],
		cTabContentId = "tabcontent_" + (currentTab.replace("tab_", "")),
		tabContentId = "tabcontent_" + tabId;

	tabId = "tab_" + tabId;
	if (currentTab !== tabId) {
		ct = document.getElementById(currentTab);
		if (ct !== null) {
            ct.className = ct.className.replace(/active/g, "");
			ct.className = ct.className.replace(/  /g, " ");
        }
		if (document.getElementById(tabId).className.indexOf(" active") === -1) {
			document.getElementById(tabId).className += " active";
		}
		if (ct !== null) {
            document.getElementById(cTabContentId).style.display = "none";
        }
		if($('#'+tabContentId).html().length == 0){
			request_url = 'content_function='+content_function+'&cf_params='+params;
			ajax_request(swapTabsHandler, window.location.pathname + '?do_ajax=1&' + request_url, boxId, tabId);
		} else {
			$('#'+tabContentId).fadeIn('slow');
			currentTabs[boxId] = tabId;
		}
	}
//	if (document.getElementById(tabContentId).firstChild.className === "scrollList") {
//		enableScroll();                //TODO where defined enableScroll
//	}
	else if (typeof(root_element) !== "undefined" && root_element !== null) {   //TODO where defined root_element
		disableScroll();                //TODO where defined disableScroll
	}
	return false;
}

function swapTabsHandler(response, request, boxId, tabId){
	var jsResult = jQuery.parseJSON(response);
	tabContentId = tabId.replace('tab_', 'tabcontent_');
	$('#'+tabContentId).html(jsResult.content);
	$('#'+tabContentId).fadeIn('slow');
	currentTabs[boxId] = tabId;
}


function serializeDateTime(){
	var root_node = document.getElementById('scheduled');
	var query_string = '';
	for(var i=0; i<root_node.childNodes.length; i++){
		current_node = root_node.childNodes[i];
		switch(current_node.type){
			case 'hidden':
				query_string += current_node.name+'='+current_node.value+'&';
				break;
			case 'select':
			case 'select-one':
				query_string += current_node.name+'='+current_node.options[current_node.selectedIndex].value+'&';
				break;
		}
	}
	if(query_string.length > 0){
		query_string = query_string.substr(0,query_string.length - 1);
	}
	return query_string;
}
