loadingCheckboxes = false;
var http = null;
var map = null;
var geocoder = null;
var popup_win = null;

function getHTTPObject() {          
        var xmlhttp;                                                     
        /*@cc_on                                                         
        @if (@_jscript_version >= 5)                                     
        try {                                                            
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");               
        }                                                            
        catch (e) {                                                      
            try {                                                        
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");        
                }                                                        
            catch (E) {                                                  
                xmlhttp = false;                                         
            }                                                        
        }                                                            
        @else                                                            
            xmlhttp = false;                                             
        @end @*/                                                         
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {          
            try {                                                            
                xmlhttp = new XMLHttpRequest();                              
            } 
            catch (e) 
            {
                xmlhttp = false;                                             
            }                                                            
        }                                                                
        
      return xmlhttp;                                                      
}
// INSTANTIATE http
http  = getHTTPObject();


function toggleSwitch (id,map_cell) {

	var d = document.getElementById(id);
	var mc = null;
	if (map_cell)
		mc = document.getElementById('map_cell');
	if (d) {
		switch (d.className){
			case 'showSwitch': 
				d.className = 'hideSwitch';
				if (mc)
					mc.className = 'map_cell_all';
				break;
			case 'hideSwitch': 
				d.className = 'showSwitch';
				if (mc)
					mc.className = 'map_cell_70';
				break;
		}
		
	}
}

function checkControlBox(childbox,controlbox) {
	if (typeof controlbox != "undefined" && !controlbox.checked && childbox.checked)
		controlbox.checked = true;
}

function clearAllBoxes(f) {

	//TODO: need to also remove all markers from the map
	//update hiddenMedia/visibleMedia

	//go through all elements
	//if they are checkboxes, set checked=false;
	for(i=0; i<f.elements.length; i++)
	{
		if (f.elements[i].type == "checkbox")
			f.elements[i].checked = false;
	}
}


/*
	//TODO: add other categories when they are functional
	
	//walk through hiddenMarkers, set all to true
	for (var prop in hiddenMarkers) {
		alert(prop);
	}

	//walk through visibleMarkers, set all to false
	// and .hide() the actual marker

	//walk through hiddenMedia, set all to true
	//walk through visibleMedia, set all to false
	
*/

function checkAllMediaBoxes(f,checked) {
	for (var i=0; i < f.elements.length; i++) {
		var e = f.elements[i];
		if (e.type == "checkbox" && e.name.indexOf("media") != -1)
			e.checked = checked;
	}
}

function saveCheckboxStates() {

	var json = getCheckboxStatesJson(document.mapcontrol_form);
	Set_Cookie("cboxes", json);

	//Now do the same thing for the instruction_form
	json = getCheckboxStatesJson(document.instruction_form);
	Set_Cookie("instruction_cboxes", json);
	
}


function getCheckboxStatesJson(f) {
	
	var media_array = "";
	var instruction_array = "";
	var type_array = "";
	var media_done = "";

	for (var i=0; i < f.elements.length; i++) {
		var e = f.elements[i];
		if (e.type == "checkbox") {
			if (e.name.indexOf("media") != -1) {
				media_array += e.value + ":" + e.checked + ",";
			} else if (e.name.indexOf("instruction") != -1) {
				instruction_array += e.value + ":" + e.checked + ",";
			} else if (e.name.indexOf("type") != -1) {
				type_array += e.value + ":" + e.checked + ",";
			}
		}
	}
	
	media_array = "{" + media_array.substring(0,media_array.length-1) + "}";
	type_array = "{" + type_array.substring(0,type_array.length-1) + "}";
	var json = "{ mediacbs: " + media_array + ", typecbs: " + type_array;
	if (instruction_array) {
		instruction_array = "{" + instruction_array.substring(0,instruction_array.length-1) + "}";
		json += ", instructioncbs:" + instruction_array;
	}
	json += "}";
	
	return json;
	
}

function loadCheckboxes() {
	loadingCheckboxes = true;

	loadCheckboxesFromCookie("cboxes",document.mapcontrol_form);
	loadCheckboxesFromCookie("instruction_cboxes",document.instruction_form);

	loadingCheckboxes = false;
	setTimeout("updateMarkers()",500);
	
}

function loadCheckboxesFromCookie(cname,f) {	

	cookie_cboxes = Get_Cookie(cname);

	if (cookie_cboxes == "null" || cookie_cboxes == null) {
		for (var i=0; i < f.elements.length; i++){
			var e = f.elements[i];
			if (e.type == "checkbox" && e.name != 'eventcb') {
				f.elements[i].checked = true;
			}
		}
		loadingCheckboxes = false;
	} else {
		media_matters = false;
		eval("var cboxes = " + cookie_cboxes + ";");
		for (var i=0; i < f.elements.length; i++){
			var e = f.elements[i];
			if (e.type == "checkbox") {
				if (e.name.indexOf("media") != -1) {
					e.checked = cboxes['mediacbs'][e.value];
				} else if ( (e.name.indexOf("instruction") != -1)) {
					e.checked = cboxes['instructioncbs'][e.value];
				} else if ( (e.name.indexOf("type") != -1)) {
					e.checked = cboxes['typecbs'][e.value];
					if (e.value in TYPES_WITH_MEDIA && e.checked) {
						media_matters = true;
					}
				}
			}
		}
	}
}

function checkAll(f,cbname,checked) {
	for (var i=0; i < f.elements.length; i++){
		if (f.elements[i].name.indexOf(cbname) != -1) {
			f.elements[i].checked = checked;
		}
	}
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
	
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function openPopup(link,width) {
	if (!width)
		width = 650;
	popup_win = window.open (link,"popup","scrollbars=yes,location=no,status=no,toolbar=no,menubar=no,width=" + width + ",height=800");
	popup_win.focus();
}

function openCouponPopup() {
	var win = window.open ("/coupon_request.php","popup","scrollbars=yes,location=no,status=no,toolbar=no,menubar=no,width=600,height=400");		
	win.focus();
}

function openDetailPopup(link) {
	if (!link)
		link = "blank.php";
	popup_win = window.open (link,"popup","scrollbars=yes,location=no,status=no,toolbar=yes,menubar=no,width=900,height=700");		
	popup_win.focus();
	if (typeof map != "undefined")
		map.getInfoWindow().hide();
}

function loadDetailPage(id) {
	openDetailPopup("detail.php?id=" + id);
}

function addToFavorites(locationid,divid)
{
	var url = BASEPATH + "/ajax/add_favorite.php";
	var params = "locationid=" + locationid;
	http.open("POST", url, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			if (http.responseText == 1) {
				document.getElementById("removefromfaves").className="showSwitch";
				document.getElementById("addtofaves").className="hideSwitch";
			} else {
				log("global.js:addToFavorites: Error " + http.responseText);
				document.getElementById(divid).innerHTML = SAVED_FAVE_ERR;
			}
		}
	}
	//Send the proper header information along with the request
	http.setRequestHeader("MessageType", "CALL")
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	http.send(params);

	//favoritesNotice();

}

function deleteFavorite(locationid,divid,detailpage)
{
	var url = BASEPATH + "/ajax/delete_favorite.php";
	var params = "locationid=" + locationid;
	http.open("POST", url, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			if (http.responseText == 1) {
				if (detailpage) {
					document.getElementById(divid).className = "hideSwitch";
				} else {
					document.getElementById("removefromfaves").className="hideSwitch";
					document.getElementById("addtofaves").className="showSwitch";
				}
			} else {
				log("global.js:addToFavorites: ERROR " + http.responseText);
				document.getElementById(divid).innerHTML = SAVED_FAVE_ERR;
			}
		}
	}
	//Send the proper header information along with the request
	http.setRequestHeader("MessageType", "CALL")
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	http.send(params);
	
	//favoritesNotice();	
	
}

function favoritesNotice() {
	//Did we already notify them about this, this session?
	var alreadyNotified = false;
	var alreadyNotified = Get_Cookie("favoritesNotice");
	if (alreadyNotified && alreadyNotified != "null")
		return;
	else {
		var userid = Get_Cookie("userid");
		var userid = Get_Cookie("userid");
		if (!userid || userid == "null") {
			//alert(msg);
		}
		Set_Cookie("favoritesNotice", "1");
	}
}

function updateWelcome(id)
{
	var url = BASEPATH + "/ajax/welcome.php";
	if (typeof id != "undefined" && id)
		url += "?id=" + id;
	http.open("GET", url, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			var div = document.getElementById('welcome_div');
			if (div) {
				div.innerHTML = http.responseText;
				setTimeout("updateWelcome()",120000);
			}
		}
	}
	//Send the proper header information along with the request
	http.setRequestHeader("MessageType", "CALL")
	http.setRequestHeader("Content-type", "html/text");
	http.setRequestHeader("Connection", "close");
	http.send();
}

function clearNewActFromSession()
{
	var url = BASEPATH + "/ajax/clear_session_newact.php";
	http.open("GET", url, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			//alert(http.responseText);
		}
	}
	//Send the proper header information along with the request
	http.setRequestHeader("MessageType", "CALL")
	http.setRequestHeader("Content-type", "html/text");
	http.setRequestHeader("Connection", "close");
	http.send();
}

function log(file,msg)
{
	var url = BASEPATH + "/ajax/log.php";
	var params = "file=" + file + "&msg=" + msg;
	http.open("POST", url, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			//alert(http.responseText);
		}
	}
	//Send the proper header information along with the request
	http.setRequestHeader("MessageType", "CALL")
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	http.send(params);
}

function emailSupport(file,msg)
{
	var url = BASEPATH + "/ajax/email_support.php";
	var params = "file=" + file + "&msg=" + msg;
	http.open("POST", url, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			//alert(http.responseText);
		}
	}
	//Send the proper header information along with the request
	http.setRequestHeader("MessageType", "CALL")
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	http.send(params);
}

function toggleMediaGroup(img,divid) {
	var div = document.getElementById(divid);
	if (div.className == "showSwitch") {
		img.src = BASEPATH + "/images/expandbtn.gif";
		div.className = "hideSwitch";
	} else {
		img.src = BASEPATH + "/images/collapsebtn.gif";
		div.className = "showSwitch";
	}
}

function toggleDiv(divid,submitbtn) {
	var div = document.getElementById(divid);
	if (div) {
		if (div.className == "showSwitch")
			div.className = "hideSwitch";
		else
			div.className = "showSwitch";
	}
	if (submitbtn) {
		var txt = submitbtn.value;
		if (txt.indexOf("Show") != -1)
			txt = txt.replace("Show","Hide");
		else
			txt = txt.replace("Hide","Show");
		submitbtn.value = txt;	
	}
}

function cbSubmit(f) {
	document.pressed = '';
	if (f.name == "instruction_form") {
		var bounds = map.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		f.northeast.value = northEast.toUrlValue();
		f.southwest.value = southWest.toUrlValue();
	}
	f.submit();

	/*
	if (f.name == "instruction_form") {
		var mediachecked = false;
		//See if any of the media checkboxes are selected
		for (var i=0; i < f.elements.length; i++){
			var e = f.elements[i];
			if (e.type == "checkbox" && (e.name.indexOf("media") != -1)) {
				if (e.checked) {
					mediachecked = true;
					break;
				}
			}
		}
		
		var artist_cb = document.getElementById("instruction_artist_cb");
		if (artist_cb) {
			if (mediachecked) {
				artist_cb.checked = true;
			} else {
				artist_cb.checked = false;
			}
		}
	}
	*/
}


function checkInstructionSearch(f) {
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	f.northeast.value = northEast.toUrlValue();
	f.southwest.value = southWest.toUrlValue();
	return true;
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                
				return true;
            }
        }
    }
    return false;
}

function removeByElement(arrayName,arrayElement) {
	for (var i=0; i<arrayName.length;i++) { 
		if (arrayName[i]==arrayElement) {
			arrayName.splice(i,1); 
			break;
		}
	} 
}



