google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){ //>
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;

google.maps.Marker.prototype.setMap = function(map) {
    if (map) {
        map.markers[map.markers.length] = this;
    }
    this._setMap(map);
}

function switchApps(appId){
	if (agent == "Custombandapp"){
		window.location = '#prefs:bandID:'+appId;
		window.location = '#initVars';
		window.location = domain+'/'+appId+'#reseedHeaders';
	}else{
		window.location = domain+'/'+appId;
	}
}


var qbSearchObj;
var searchStruct;
function setUpSearchObj(){
	try {
		qbSearchObj = new Object();
		qbSearchObj.app_id = bandId;
		qbSearchObj.user_id = userId;
		qbSearchObj.interface_type = "front_end";
		qbSearchObj.query = 'voter_search';
		qbSearchObj.limit = 15;
		qbSearchObj.machine_id = machine_id;
		qbSearchObj.sort = 'name';
		qbSearchObj.display_fields = 524290;
		qbSearchObj.search_terms;
		
		searchStruct = [];
		
	}catch(e){
		alert(e.message);
	}
}

function showQBSortOption(hideShowToggle){
	if (hideShowToggle == 0){
		document.getElementById('qbSortOptions').style.display = "none";
	}else if (hideShowToggle == 1){
		document.getElementById('qbSortOptions').style.display = "block";
	}else{
		document.getElementById('qbSortOptions').style.display = document.getElementById('qbSortOptions').style.display == "none" ? "block" : "none";
	}
}


function setQBSort(type,desig,id){
	if (!qbSearchObj || !searchStruct) setUpSearchObj();
	
	document.getElementById('qbSort_'+qbSearchObj.sort).className = '';
	document.getElementById('qbSort_'+type).className = 'currentSort';
	
	qbSearchObj.sort = type;
	if (type == 'distance'){
		qbSearchObj.latitude = lat
		qbSearchObj.longitude = lon;
	}

	qbSearchObj.search_terms && qbAjaxSend(desig,id);
	document.getElementById('qbSortOptions').style.display = "none";
}

var qbSearchableFields = [];
function qbsearch(searchFld,desig,id){
	try{
		if(searchFld.style.color == "gray"){
			var tempVal = searchFld.value.substr(searchFld.title.length,1)
			searchFld.style.color = "black";
			searchFld.value = tempVal;
		}
		showQBSortOption(0);
		moveBackBar(0);
		if (!qbSearchObj || !searchStruct) setUpSearchObj();
		if (searchFld.value != searchFld.title){
			qbSearchableFields[searchFld.id] = searchFld.id;
			searchStruct = [];
			var qbstrlen = '';
			for(fieldIndex in qbSearchableFields){
				qbstrlen += document.getElementById(qbSearchableFields[fieldIndex]).value; 
			}
			for(fieldIndex in qbSearchableFields){ 
				if (fieldIndex && document.getElementById(qbSearchableFields[fieldIndex]).value != '' && document.getElementById(qbSearchableFields[fieldIndex]).value != ' ' && document.getElementById(qbSearchableFields[fieldIndex]).value != document.getElementById(qbSearchableFields[fieldIndex]).title) {
					searchStruct[qbSearchableFields[fieldIndex]] = {"field":document.getElementById(qbSearchableFields[fieldIndex]).title.toLowerCase().replace(" ","_"),"value":document.getElementById(qbSearchableFields[fieldIndex]).value,"prefix":qbstrlen.length>1?1:0};
				}
			}
			qbSearchObj.search_terms = [];
			for(searchStringObj in searchStruct) searchStruct[searchStringObj] && qbSearchObj.search_terms.push(searchStruct[searchStringObj]);
			qbAjaxSend(desig,id);
		}
	}catch(e){
		errorLog(['qbsearch',e.message,false]);
	}
}

var qbAjax;
function qbAjaxSend(desig,id){
	if (qbAjax){
		qbAjax.abort();
	}
	if (qbAjax = new ajaxObj()){
		var rightnow = new Date();
		var postString = domain+'/scripts/qbProxy.php?'+rightnow.getTime();
		qbAjax.open('POST',postString,true);
		qbAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		qbAjax.send('&data='+JSON.stringify(qbSearchObj));
		
		qbAjax.onreadystatechange = function () {
			if (qbAjax && qbAjax.status == 200 && qbAjax.readyState == 4){
				if (qbAjax.responseText != ''){
					var result = JSON.parse(qbAjax.responseText);
					if (result.result == "ok" && !result.note && result.max_hits > 0) {
						buildqbResults(result,desig,id);
					}else{
						document.getElementById('qbResultsPane').innerHTML = "No Results";
						document.getElementById('qbResultsPane').style.display = "block";
					}
				}
			}
		}
		
	}else{
		errorLog(['qbsearch','ajaxObject failed',false]);
	}
}

var fromQBSearch = 0;
function buildqbResults(result,desig,id){
	var resultsElem = document.getElementById('qbResultsPane');
	resultsElem.innerHTML = '';
	document.getElementById('qbNumResults').innerHTML = (result.max_hits + 0 == result.max_hits) ? result.max_hits : 0;
	for(record in result.results){
		var recordElem = document.createElement('a');
		recordElem.className = "qbRecordDiv";
		recordElem.href="javascript:showDatasetDetails('"+desig+"',"+id+","+result.results[record].id+",1)";
		recordElem.id = "qbRecord_"+result.results[record].id
		
		var recordName = document.createElement('span');
		recordName.className = "qbRecordName";
		recordName.innerHTML = result.results[record].name;
		recordElem.appendChild(recordName);
		
		var recordAddress = document.createElement('span');
		recordAddress.className = "qbRecordAddress";
		recordAddress.innerHTML = result.results[record].address;
		recordElem.appendChild(recordAddress);
		
		resultsElem.appendChild(recordElem);
	}
		
	resultsElem.style.display = "block";

}

var backBarIsHidden = -1;
var currentBBState;
function moveBackBar(onOff){
	currentBBState = document.getElementById('backBar').style.display;
	if (onOff == 2){
		document.getElementById('backBar').style.display = currentBBState;
		document.getElementById('bbackBar').style.display = "none";
		backBarIsHidden = 0;
	}else if(onOff == 1){
		document.getElementById('backBar').style.display = "block";
		document.getElementById('bbackBar').style.display = "none";
		backBarIsHidden = 1;
	}else{
		document.getElementById('bbackBar').style.display = "block";
		document.getElementById('backBar').style.display = "none";
		backBarIsHidden = 0;
	}	
}

function ajaxObj(){
	var aObj;
	try {
		aObj = new XMLHttpRequest();
	}catch (e){
		alert(e.message);
		try {
			aObj = new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			try {
				aObj = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {
				aObj = false;
			}
		}
	}
	return aObj;
}

function eulaCancel(){
	window.location.href= domain+"/eula/canceled_agreement/"+bandId+"#extURL";
}

function errorLog(vars){
	var functionName = vars[0];
	var messageText = vars[1];
	var willContinue = vars[2];
	if (ajaxObject = new ajaxObj()){
		try{
			var data = {'app_id':bandId,'func':functionName,'message':messageText};
			
			var rightnow = new Date();
			var postString = '/logging/jsError?tS='+rightnow.getTime();
			
			ajaxObject.open('POST',postString,true);
			ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			
			ajaxObject.send('&data='+JSON.stringify(data).replace(/\+/g,'%2b'));
			
		}catch(e){
			//
		}finally{
			activityIndicator(0);
			if (willContinue == false){
				popConfirm("There was a problem with the request. The service may be temporarily down for maintenance. Press OK to try again","jsErrorAlert","javascript:reloadOrReturnHome(0)","javascript:reloadOrReturnHome(1)");
			}
		}
	}
}

function testError(){
	popConfirm("test alert","jsErrorAlertTest","javascript:reloadOrReturnHome(0)","javascript:reloadOrReturnHome(1)");
}

function reloadOrReturnHome(choice){
	//0 = reload, 1 = return home
	switch (choice){
		case 0:
			if (agent == "Custombandapp"){
				redoCurrentRequest();
			}else{
				window.location.reload();
			}
			break;
		case 1:
			if (agent == "Custombandapp"){
				returnHome();
			}else{
				returnHome();
			}
			break;
	}
	
}

function eulaAgree(){
	if (clientInfo['uuid'] != "" && clientInfo['uuid'] != undefined) {
		if (ajaxObject = new ajaxObj()){
			try{
				var rightnow = new Date();
				var getString = '/eula/eulaAgreed/'+bandId+'/'+clientInfo['uuid']+'?tS='+rightnow.getTime();
				ajaxObject.open('GET',getString,true);
				ajaxObject.send(null);
				ajaxObject.onreadystatechange = function () {
					try{
						if(ajaxObject.readyState == 4) {
							if (ajaxObject && ajaxObject.status == 200){
								document.getElementById('eulaWindow').innerHTML = '';
								document.getElementById('eulaWindow').style.display = "none";
								document.body.removeChild(document.getElementById('eulaWindow'));
								eulaOpen = false;
								window.location.href="#eulaAccept";
								resetLinks();
							}
						}
					}catch(e){
						errorLog(['eulaAgree',e.message,false]);
					}
				}
			}catch(e){
				errorLog(['eulaAgree',e.message,false]);
			}
		}else{
			errorLog(['eulaAgree','ajaxObject failed',false]);
		}
	}else{
		try{
			document.getElementById('eulaWindow').innerHTML = '';
			document.getElementById('eulaWindow').style.display = "none";
			document.body.removeChild(document.getElementById('eulaWindow'));
			eulaOpen = false;
		}catch(e){
			errorLog(['eulaAgree',e.message,false]);
		}
	}
}

function returnHome(){
	window.location.href = "/"+bandId+"#refresh";
	window.location.href = "/"+bandId;
}

var ajaxLogoutObject;
function logout(){
	popConfirm("Logout?","logoutConfirm","javascript:logoutAction()",'');
}

function logoutAction(){
	if (ajaxLogoutObject = new ajaxObj()){
		try{
			var rightnow = new Date();
			var logoutString = '/canvassing/logout?id='+bandId+'&tS='+rightnow.getTime();
			ajaxLogoutObject.open('GET',logoutString,true);
			ajaxLogoutObject.send(null);
			ajaxLogoutObject.onreadystatechange = function(){
				try{
					if (ajaxLogoutObject && ajaxLogoutObject.status == 200){
						if (agent == "Custombandapp"){
							window.location.href = '#gglogout';
						}else{
							window.location.href = '/'+bandId;
						}
					}
				}catch(e){
					errorLog(['logoutAction',e.message,false]);
				}
			}
		}catch(e){
			errorLog(['logoutAction',e.message,false]);
		}
	}else{
		errorLog(['logoutAction','ajaxObject failed',false]);
	}
}

function socketErrAction(){
	activityIndicator(0);
	popConfirm("There was a problem with the request. The service may be temporarily down for maintenance. Press OK to try again","socketErrorAlert","javascript:window.location.reload()","javascript:returnHome()");
}

function saveQuestion(questionnaire_id,detailsId,designator,featureId){
	
	try{
		activityIndicator(1);
		var data = new Object();
		var responses = new Array();
		data.questionnaire_id = parseInt(document.getElementById(designator+'_'+featureId+'_questionnaire_id').value);
		data.voter_id = parseInt(document.getElementById(designator+'_'+detailsId+'_voter_id').options[document.getElementById(designator+'_'+detailsId+'_voter_id').selectedIndex].value);
		var questionCount = document.getElementById(designator+'_'+featureId+'_'+questionnaire_id+'_question_count').value;
		data.geo_y = parseFloat(document.getElementById(designator+'_'+featureId+'_venue_lat').value);
		data.geo_x = parseFloat(document.getElementById(designator+'_'+featureId+'_venue_long').value);
	
		for (var i = 0; i < questionCount; ++i) { //>
			switch(document.getElementById('question_type_'+i+'_'+questionnaire_id+'_'+detailsId).value){
				case "choose_one":
					responses[i] = parseInt(document.getElementById('question_'+i+'_'+questionnaire_id+'_'+detailsId).options[document.getElementById('question_'+i+'_'+questionnaire_id+'_'+detailsId).selectedIndex].value);
					break;
				case "choose_many":
					var optionIds = document.getElementById('question_options_'+i+'_'+questionnaire_id+'_'+detailsId).value.split(',');
					responses[i] = new Array();
					for(var j in optionIds){
						var checkedVal = document.getElementById('question_'+i+'_'+questionnaire_id+'_'+detailsId+'_'+optionIds[j]).checked;
						if (checkedVal){
							responses[i].push(parseInt(optionIds[j]));
						}
					}				
					break;
				case "text":
					responses[i] = document.getElementById('question_'+i+'_'+questionnaire_id+'_'+detailsId).value;
					break;
				default:
			}
		}	
		data.responses = responses;
	
		var ajaxQuestionObject;
		if (ajaxQuestionObject = new ajaxObj()){
			var rightnow = new Date();
			ajaxQuestionObject.open('POST','/dataset/savequestion/'+bandId+'?tS='+rightnow.getTime(),true);
			ajaxQuestionObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			ajaxQuestionObject.send('&data='+JSON.stringify(data));
			ajaxQuestionObject.onreadystatechange = function(){
				try{
					if(ajaxQuestionObject && ajaxQuestionObject.readyState == 4 && ajaxQuestionObject.status == 200){
						var result = JSON.parse(ajaxQuestionObject.responseText);
						if (result.result = "ok"){
							notSaved = false;
							document.getElementById('visited_flag_'+data.voter_id).innerHTML = 'visited';
							activityIndicator(0);
							document.getElementById('hasSaved_'+detailsId).style.display = "block";
							document.getElementById('saveButton_'+detailsId).style.display = "none";
						}
					}
				}catch(e){
					errorLog(['saveQuestion',e.message,false]);
				}
			}
		}else{
			errorLog(['saveQuestion','ajaxObject failed',false]);
		}
	}catch(e){
		errorLog(['saveQuestion',e.message,false]);
	}
	
}

function getResponsesForVoter(voterId,designator,questionnaireId,detailsId){
	try{
		activityIndicator(1);
		if (notSaved){
			if(confirm("Changes have not been saved!")){
				notSaved = false;
			}else{
				document.getElementById(designator+'_'+detailsId+'_voter_id').value = document.getElementById('selected_voter').value;
				activityIndicator(0);
				return;
			}
		} 
		var ajaxQuestionObject;
		if (ajaxQuestionObject = new ajaxObj()){
			var rightnow = new Date();
			var postString = '/dataset/getresponsesforvoter/'+bandId+'/'+voterId+'/'+questionnaireId+'?tS='+rightnow.getTime();
			ajaxQuestionObject.open('GET',postString,true);
			ajaxQuestionObject.send();
			ajaxQuestionObject.onreadystatechange = function () {
				try{
					if(ajaxQuestionObject.readyState == 4) {
						if (ajaxQuestionObject && ajaxQuestionObject.status == 200){
							var result = JSON.parse(ajaxQuestionObject.responseText);
							for (var i in result){
								if (document.getElementById('question_type_'+i+'_'+questionnaireId+'_'+detailsId)){
									switch (document.getElementById('question_type_'+i+'_'+questionnaireId+'_'+detailsId).value){
										case "choose_one":
											document.getElementById('question_'+i+'_'+questionnaireId+'_'+detailsId).value = result[i];
											break;
										case "choose_many":
											var allOpts = document.getElementById('question_options_'+i+'_'+questionnaireId+'_'+detailsId).value.split(',');
											for (var k in allOpts){
												document.getElementById('question_'+i+'_'+questionnaireId+'_'+detailsId+'_'+allOpts[k]).checked = false;
											}
											for (var j in result[i]){
												document.getElementById('question_'+i+'_'+questionnaireId+'_'+detailsId+'_'+result[i][j]).checked = true;
											}
											break;
										case "text":
											document.getElementById('question_'+i+'_'+questionnaireId+'_'+detailsId).value = result[i];
											break;
										default:
									}
									
								}
							}
							scrollTo(0,0);
							activityIndicator(0);
						}
					}
				}catch(e){
					errorLog(['getResponsesForVoter',e.message,false]);
				}
			}
		}else{
			errorLog(['getResponsesForVoter','ajaxObject failed',false]);
		}
		document.getElementById('selected_voter').value = document.getElementById(designator+'_'+detailsId+'_voter_id').value;
	}catch(e){
		errorLog(['getResponsesForVoter',e.message,false]);
	}
}

var notSaved = false;
function unsaved(detailsId){
	try{
		notSaved = true;
		document.getElementById('hasSaved_'+detailsId).style.display = "none";
		document.getElementById('saveButton_'+detailsId).style.display = "block";
	}catch(e){
		errorLog(['unsaved',e.message,false]);
	}
}

var defaultFrom = '';
function emailWindow(emailId){
	try{
		if(agent == 'Custombandapp'){ 
			activityIndicator(1);
			emailBodyId = emailId;
			var emailWindowDiv = document.createElement('div');
			emailWindowDiv.setAttribute('id','emailWindow');
			document.body.appendChild(emailWindowDiv);
			if (ajaxObject = new ajaxObj()){
				var rightnow = new Date();
				var postString = '/contacts/getCannedEmail/'+bandId+'/'+emailBodyId+'?tS='+rightnow.getTime();
				ajaxObject.open('POST',postString,true);
				ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				ajaxObject.send('&from='+defaultFrom+'&subject='+document.title); //add from eventually
				ajaxObject.onreadystatechange = function () {
					try{
						if(ajaxObject.readyState == 4) {
							if (ajaxObject && ajaxObject.status == 200){
								document.getElementById('emailWindow').innerHTML = ajaxObject.responseText;
								document.getElementById('emailWindow').style.display = "block";
								contactsListOpen = true;
								activityIndicator(0);
							}
						}
					}catch(e){
						errorLog(['emailWindow',e.message,false]);
					}
				}
			}else{
				errorLog(['emailWindow','ajaxObject failed',false]);
			}
		}
	}catch(e){
		errorLog(['emailWindow',e.message,false]);
	}
}

var emailBodyId;
var contactsListOpen = false;
function contactWindow(contactsString,offset,emailId){
	try{
		if(agent == 'Custombandapp'){ 
			activityIndicator(1);
			emailBodyId = emailId;
			var contactWindowDiv = document.createElement('div');
			contactWindowDiv.setAttribute('id','contactWindow');
			document.body.appendChild(contactWindowDiv);
			if (ajaxObject = new ajaxObj()){
				var rightnow = new Date();
				var postString = '/contacts/index/'+bandId+'/'+emailBodyId+'?tS='+rightnow.getTime();
				ajaxObject.open('POST',postString,true);
				ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				ajaxObject.send('&offset='+offset+'&data='+contactsString);
				ajaxObject.onreadystatechange = function () {
					try{
						if(ajaxObject.readyState == 4) {
							if (ajaxObject && ajaxObject.status == 200){
								document.getElementById('contactWindow').innerHTML = ajaxObject.responseText;
								if (document.getElementById('emailWindow')){
									document.getElementById('emailWindow').style.zIndex = "1";
								}
								document.getElementById('contactWindow').style.zIndex = "100";
								document.getElementById('contactWindow').style.display = "block";
								contactsListOpen = true;
								activityIndicator(0);
								recheckContacts();
							}
						}
					}catch(e){
						errorLog(['contactWindow',e.message,false]);
					}
				}
			}else{
				errorLog(['contactWindow','ajaxObject failed',false]);
			}
		}
	}catch(e){
		errorLog(['contactWindow',e.message,false]);
	}
}

var eulaBodyId;
var eulaOpen = false;
function eulaWindow(eulaId){
	try{
		eulaBodyId = eulaId;
		var eulaWindowDiv = document.createElement('div');
		eulaWindowDiv.setAttribute('id','eulaWindow');
		document.body.appendChild(eulaWindowDiv);
		var eulaAjaxObject;
		if (eulaAjaxObject = new ajaxObj()){
			var rightnow = new Date();
			var getString = '/eula/index/'+bandId+'/'+eulaBodyId+'?tS='+rightnow.getTime();
			eulaAjaxObject.open('GET',getString,true);
			eulaAjaxObject.send(null);
			eulaAjaxObject.onreadystatechange = function () {
				try{
					if(eulaAjaxObject.readyState == 4) {
						if (eulaAjaxObject && eulaAjaxObject.status == 200){
							document.getElementById('eulaWindow').innerHTML = eulaAjaxObject.responseText;
							document.getElementById('eulaWindow').style.zIndex = "100";
							document.getElementById('eulaWindow').style.display = "block";
							eulaOpen = true;
						}
					}
				}catch(e){
					errorLog(['eulaWindow',e.message,false]);
				}
			}
		}else{
			errorLog(['eulaWindow','ajaxObject failed',false]);
		}
	}catch(e){
		errorLog(['eulaWindow',e.message,false]);
	}
}



function checkItem(contactId,email){
	try{
		document.getElementById('selectContact_'+contactId).checked = !document.getElementById('selectContact_'+contactId).checked;
		if (document.getElementById('selectContact_'+contactId).checked){
			addContactToList(contactId,email);
		}else{
			contactListArray[contactId] = "";
		}
	}catch(e){
		errorLog(['checkItem',e.message,false]);
	}
}

function recheckContacts(){
	try{
		for(var i in contactListArray){
			if (document.getElementById('selectContact_'+i) && contactListArray[i] != ""){
				document.getElementById('selectContact_'+i).checked = true;
			}
		}
	}catch(e){
		errorLog(['recheckContacts',e.message,false]);
	}
}

function closeContatList(){
	try{
		if (document.getElementById('contactWindow')){
			document.getElementById('contactWindow').innerHTML = "";
			document.getElementById('contactWindow').style.display = "none";
			document.body.removeChild(document.getElementById('contactWindow'));
			contactsListOpen = false;
		}
	}catch(e){
		errorLog(['closeContatList',e.message,false]);
	}
}

function closeEmailWindow(){
	try{
		if (document.getElementById('emailWindow')){
			document.getElementById('emailWindow').innerHTML = "";
			document.getElementById('emailWindow').style.display = "none";
			document.body.removeChild(document.getElementById('emailWindow'));
		}
	}catch(e){
		errorLog(['closeEmailWindow',e.message,false]);
	}
}


var contactListArray = new Array();
function addContactToList(contactId,email){
	contactListArray[contactId] = email;
}

function emailContactList(){
	try{
		if (contactListArray.length > 0){
			var emailBody = document.getElementById('email_body').value;
			var emailBodyStripped = emailBody.replace(new RegExp( "\\n\\r", "g" ),"");
			var from = document.getElementById('email_from').value;
			defaultFrom = from;
			var subject = document.getElementById('email_subject').value;
			var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	    	if(!pattern.test(from)){
	    		alert("Please provide a valid email address.");
	    		return;
	    	}
			if (ajaxObject = new ajaxObj()){
				var rightnow = new Date();
				ajaxObject.open('POST','/contacts/sendCannedEmail/'+emailBodyId+'/'+bandId+'?tS='+rightnow.getTime(),true);
				ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				ajaxObject.send('&body='+emailBodyStripped+'&from='+from+'&subject='+subject+'&recpts='+JSON.stringify(contactListArray));
				activityIndicator(1);
				window.scrollTo(0, 0);
				ajaxObject.onreadystatechange = function () {
					try{
						if(ajaxObject.readyState == 4) {
							if (ajaxObject && ajaxObject.status == 200){
								closeEmailWindow();
								activityIndicator(0);
								alert("Email Sent!");
							}
						}
					}catch(e){
						errorLog(['emailContactList',e.message,false]);
					}
				}
			}else{
				errorLog(['emailContactList','ajaxObject failed',false]);
			}
		}else{
			alert("No recipients were added!");
		}
	}catch(e){
		errorLog(['emailContactList',e.message,false]);
	}
}

function popAlert(message,id){
	try{
		if (document.getElementById(id)) {
			document.body.removeChild(document.getElementById(id));
		}
		var popElem = document.createElement("div");
		popElem.setAttribute("id",id);
		popElem.setAttribute("class","popAlert");
		var elemContA = document.createElement("div");
		var elemContB = document.createElement("div");
		
		var wordcount = message.split(' ').length;
		var newTop = 150;
		if (wordcount > 0) newTop = (150 - (3*wordcount));
		if (newTop < 10) newTop = 10 //>
		popElem.setAttribute("style","top:"+newTop+"px");
		
		elemContB.innerHTML += "<span>"+message+"</span>";
		
		var elemOkButton = document.createElement("a");
		elemOkButton.setAttribute("href","javascript:closePopAlert('"+id+"')");
		elemOkButton.setAttribute("class","popok popsingle");
		elemOkButton.innerHTML = "OK";
		elemContB.appendChild(elemOkButton);
		
		var elemClearBoth = document.createElement("b");
		elemClearBoth.setAttribute("class","clearBoth");
		elemContB.appendChild(elemClearBoth);
		
		elemContA.appendChild(elemContB);
		popElem.appendChild(elemContA);
		document.body.appendChild(popElem);
		
		window.scrollTo(0,0);
	}catch(e){
		errorLog(['popAlert',e.message,false]);
	}
}

function popConfirm(message,id,actionOK,actionCancel){
	try{
		if (document.getElementById(id)) {
			document.body.removeChild(document.getElementById(id));
		}
		var popElem = document.createElement("div");
		popElem.setAttribute("id",id);
		popElem.setAttribute("class","popAlert");
		var elemContA = document.createElement("div");
		var elemContB = document.createElement("div");
		
		var wordcount = message.split(' ').length;
		var newTop = 150;
		if (wordcount > 0) newTop = (150 - (3*wordcount));
		if (newTop < 10) newTop = 10 //>
		popElem.setAttribute("style","top:"+newTop+"px");
		
		elemContB.innerHTML += "<span>"+message+"</span>";
		
		var elemCancelButton = document.createElement("a");
		elemCancelButton.setAttribute("href","javascript:closePopAlert('"+id+"')");
		if (!actionCancel) actionCancel = '';
		elemCancelButton.setAttribute("href","javascript:closePopAlert('"+id+"');"+actionCancel);
		elemCancelButton.setAttribute("class","popcancel popdouble");
		elemCancelButton.innerHTML = "Cancel";
		elemContB.appendChild(elemCancelButton);
		
		var elemOkButton = document.createElement("a");
		if (!actionOK) actionOK = '';
		elemOkButton.setAttribute("href",actionOK+";javascript:closePopAlert('"+id+"')");
		elemOkButton.setAttribute("class","popok popdouble");
		elemOkButton.innerHTML = "OK";
		elemContB.appendChild(elemOkButton);
		
		var elemClearBoth = document.createElement("b");
		elemClearBoth.setAttribute("class","clearBoth");
		elemContB.appendChild(elemClearBoth);
		
		elemContA.appendChild(elemContB);
		popElem.appendChild(elemContA);
		document.body.appendChild(popElem);
		
		window.scrollTo(0,0);
	}catch(e){
		errorLog(['popConfirm',e.message,false]);
	}
}

function closePopAlert(elemId){
	try{
		document.getElementById(elemId).style.display = "none";
		document.body.removeChild(document.getElementById(elemId));
	}catch(e){
		errorLog(['closePopAlert',e.message,false]);
	}
}

function returnFBJSON(){
	try{
		var elemId = document.getElementById('currentCommand').value.replace(/\//g,'_');
		
		var fbPost = new Object();
		fbPost.name = getSocialDatum('titleSocialpost');
		fbPost.href = getSocialDatum('hrefSocialpost');
		fbPost.description = getSocialDatum('descSocialpost');
		
		if(getSocialDatum('mediaSocialpost') && getSocialDatum('mediaSocialpost') != "") {
			var mediaObj = new Object();	
			mediaObj.type = "image";
			mediaObj.src = getSocialDatum('mediaSocialpost');
			mediaObj.href = getSocialDatum('hrefSocialpost');
			
			var mediaArray = new Array();
			mediaArray.push(mediaObj);
			
			fbPost.media = mediaArray;
		}
		
		return JSON.stringify(fbPost);	
	}catch(e){
		errorLog(['returnFBJSON',e.message,false]);
	}
} 

function returnTWPost(){
	return socialTitle() + " " + socialHREFBitly();
}

function socialTitle(){
	return getSocialDatum('titleSocialpost');
}

function socialHREFBitly(){
	return getSocialDatum('hrefSocialpostBitly');
}

function socialHREF(){
	return getSocialDatum('hrefSocialpost');
}

function socialDesc(){
	return getSocialDatum('descSocialpost');
}

function socialMedia(){
	return getSocialDatum('mediaSocialpost');
}

function getSocialDatum(socialField) {
	try{
		var elemId = document.getElementById('currentCommand').value.replace(/\//g,'_');
		return document.getElementById(socialField+elemId).value;
	}catch(e){
		errorLog(['getSocialDatum',e.message,false]);
	}
}

var isAjaxRunning = 0;
var ajaxObject = null;
var getDesigBool = false;
function fireAjax(command,target){
		if(isAjaxRunning != 1) {
			return false;		
		}
				
		isAjaxRunning = 2;
		
		if(agent == 'Custombandapp'){ cancelTimedItem(); }
		var targetDiv = document.getElementById(target);
		var commandParams = command.split("/");
		if (commandParams[1] == 'dataset' && commandParams[2] == 'index'){
			currentMapFeatureId = commandParams[3];
			getDesigBool = true;
		}
		var timeLength = tis[commandParams[commandParams.length - 1]];
		var itemTimed = 0;
		if (timeLength > -1) itemTimed = 1;
		document.getElementById('currentCommand').value=command;
		
		if (document.getElementById('feature_meta_'+currentMapFeatureId+'_always_refresh') &&
			document.getElementById('feature_meta_'+currentMapFeatureId+'_always_refresh').value == 1){
			targetDiv.innerHTML = '';
			refreshTarget = false;
		}
		
		if (targetDiv.innerHTML == '' || itemTimed > 0){
			activityIndicator(1);
			
			if (ajaxObject){
				if(agent == 'Custombandapp') { cancelTimeout(); }
			}
			
			if (ajaxObject = new ajaxObj()){
				var rightnow = new Date();			
				
				/* Due to issues with syncronous ajax and webOS we have had to write in a check and run a different ajax request for webOS */
				if(isWebOS == true) {				
					ajaxObject.open('GET',command+'?bandId='+bandId+'&tS='+rightnow.getTime(),true);
					ajaxObject.onreadystatechange = function () { 
						if(ajaxObject.readyState == 4) {
							if (ajaxObject && ajaxObject.status == 200 && isAjaxRunning == 2){
								cancelTimedItem();
								var oldgapage = document.getElementById('gapage');
								if(oldgapage != null) {
									oldgapage.parentNode.removeChild(oldgapage);
								}
								targetDiv.innerHTML = '';
								try{
									var response = JSON.parse(ajaxObject.responseText)
									if (response.success == 0 && response.result == 'logout'){
										logoutAction();
										return false;
									}
									if (response.success == 0 && response.result == 'socketError'){
										socketErrAction();
										return false;
									}
								}catch(e){
									//fail; continue
								}
								targetDiv.innerHTML = ajaxObject.responseText;
								showError();
								if (getDesigBool){
									if (!document.getElementById('dataset_designator_'+currentMapFeatureId)){
										returnHome();
										return false;
									}
									currentMapDataset = document.getElementById('dataset_designator_'+currentMapFeatureId).value;
									getDesigBool = false;
								}
			
								pageTransition(target,1);
			
								if(document.getElementById('gapage') != null) {;
									var gapagevalue = document.getElementById('gapage').value;
									_gaq.push(['_trackPageview',gapagevalue]);
									if(hasMoonTracker) {
										_gaq.push(['b._trackPageview',gapagevalue]);
									}
								}
								ajaxObject = null;
								isAjaxRunning = 0;
							}
						}
				
					}
					ajaxObject.send(null);
				} else {
					startTimeOut(command);
					ajaxObject.open('GET',command+'?bandId='+bandId+'&tS='+rightnow.getTime(),false);
					try{ 
						ajaxObject.send(null);
					}catch(e){
						if (e.name == 'NETWORK_ERR'){
							errorLog(['fireAjax','NETWORK_ERR',true]);
							fireAjax(command,target);
							return;
						}
					}
					if (ajaxObject && ajaxObject.status == 200){
						cancelTimeout();
						
						var oldgapage = document.getElementById('gapage');
						if(oldgapage != null) {
							oldgapage.parentNode.removeChild(oldgapage);
						}					
						
						try{
							var response = JSON.parse(ajaxObject.responseText)
							if (response.success == 0 && response.result == 'logout'){
								logoutAction();
								return false;
							}
							if (response.success == 0 && response.result == 'socketError'){
								socketErrAction();
								return false;
							}
						}catch(e){
							//fail; continue
						}
						
						targetDiv.innerHTML = '';
						targetDiv.innerHTML = ajaxObject.responseText;
						showError();
						
						if (getDesigBool){
							if (!document.getElementById('dataset_designator_'+currentMapFeatureId)){
								returnHome();
								return false;
							}
							currentMapDataset = document.getElementById('dataset_designator_'+currentMapFeatureId).value;
							getDesigBool = false;
						}
																
						pageTransition(target,1);
						adjustBackButton();
						if(document.getElementById('gapage') != null) {;
							var gapagevalue = document.getElementById('gapage').value;		
							
					 		//_gaq.push(['_setAccount','<?= (strlen($googleAnalyticsCode) > 0) ? $googleAnalyticsCode : 'UA-9264241-3'; ?>']);
					 		_gaq.push(['_trackPageview',gapagevalue]);
	
							if(hasMoonTracker) {
								//_gaq.push(['b._setAccount','<?= $googleAnalyticsCodeMoon ?>']);
								_gaq.push(['b._trackPageview',gapagevalue]);					
							}
						}
					}
										
					var lastModified = ajaxObject.getResponseHeader("Last-modified");
					if(lastModified && lastModified.length > 0) {
						var theNewDiv = document.createElement("input");
						theNewDiv.setAttribute("type","hidden");
						theNewDiv.setAttribute("value",lastModified);
						theNewDiv.setAttribute("id",command.replace(/\//g,'_')+"_last_mod");
						targetDiv.appendChild(theNewDiv);
					}	
					
					ajaxObject = null;
					isAjaxRunning = 0;
				}
			}else{
				errorLog(['fireAjax','ajaxObject failed',true]);
			}
		}else{
			pageTransition(target,1);
			if (getDesigBool){
				if (!document.getElementById('dataset_designator_'+currentMapFeatureId)){
					returnHome();
					return false;
				}
				currentMapDataset = document.getElementById('dataset_designator_'+currentMapFeatureId).value;
				getDesigBool = false;
			}
			resetSearch();
			adjustBackButton();
			
			isAjaxRunning = 0;
		}
	//}catch(e){
	//	errorLog(['fireAjax 5',e.message,true]);
	//}
}

function resetSearch(){
	try{
		if (document.getElementById('search_div')){
			document.getElementById('results_div').style.display = "none";
			document.getElementById('details_div').style.display = "none";
			document.getElementById('search_div').style.display = "block";
		}
	}catch(e){
		errorLog(['resetSearch',e.message,false]);
	}
}

function getLastModForItem(item) {
	try{
		var lastModDate = document.getElementById(item+'_last_mod');
		if(lastModDate != false) {
			return lastModDate.value;
		}
		
		return false;
	}catch(e){
		errorLog(['getLastModForItem',e.message,false]);
	}
}

var timedItemTimer;
function startTimedItem(command,target,tlen){
	try{
		timedItemTimer = setTimeout('fireAjax("'+command+'","'+target+'")',(tlen * 60 * 1000));
	}catch(e){
		errorLog(['startTimedItem',e.message,false]);
	}
}

function cancelTimedItem(){
	clearTimeout(timedItemTimer);
}

var timeOut;
function startTimeOut(command){
	timeOut = setTimeout('checkConnection("'+command+'")',20000);
}

function cancelTimeout(){
	if (timeOut){
		clearTimeout(timeOut);
	}
}

function checkConnection(command){
	if(agent == 'Custombandapp'){
		window.location.href = '#conAlert:webAction:'+command;
	}
}

function nextPrevNewsItem(command){
	skipStackBool = 1;
	doRequest(command);
}

function reloadWebCommand(command){
	var divName = command.replace(/\//g,'_');
	fireAjax(command,divName);
}

function createDiv(divName){
	try{
		if (!document.getElementById(divName)){
			var divCon = document.getElementById('divcon');
			var newdiv = document.createElement('div');
			newdiv.setAttribute('id',divName);
			newdiv.setAttribute('class','container');
			divCon.appendChild(newdiv);
		}
	}catch(e){
		errorLog(['startTimedItem',e.message,false]);
	}
}

var doRequestTotalCount = 0;
var doRequestCount = 0;
function doRequest(command,itemName) {
	try{
		doRequestCount++;
		if(isAjaxRunning != 0 || doRequestCount != 1) {
			doRequestCount--;
			return false; 
		}
		
		if(hasLoaded != 1) {
			doRequestCount--;
			return false;
		}
		
		isAjaxRunning = 1;
		doRequestTotalCount++;
		
		var divName = command.replace(/\//g,'_');
		if(agent != 'Custombandapp'){
			window.location = "#"+divName;
		}
		createDiv(divName);
		pageStacker(command,divName,itemName);
		
		fireAjax(command,divName);
		doRequestCount--;
	}catch(e){
		errorLog(['doRequest',e.message,false]);
	}
}

function redoCurrentRequest(){
	try{
		var command = document.getElementById('currentCommand').value;
		if (command == undefined) return false;
		if (pageStack[pageStack.length - 1]['command'] == command){
			var itemName = pageStack[pageStack.length - 1]['itemName'];
			skipStackBool = 1;
			doRequest(command,itemName);
		}
	}catch(e){
		errorLog(['redoCurrentRequest',e.message,false]);
	}
}

var pageStack = new Array();
function pageStacker(command,target,itemName){
	try{
		var page = new Array(); 
		page['command'] = command;
		page['target'] = target;
		if (itemName == undefined){
			page['itemName'] = 'Back';
		}else{
			page['itemName'] = itemName;
		}
		pageStack.push(page);
	}catch(e){
		errorLog(['pageStacker',e.message,false]);
	}
	
}

function previous(){
	try{
		cancelTimedItem();
		var page = pageStack.pop();
		
		pageTransition(page['target'],0);
		adjustBackButton();
		if(agent != 'Custombandapp'){
			var iserr = false;
			if (location.search){
				var urlquery = location.search.split('&');
				for (var i = 0; i < urlquery.length; ++i){ //>
					var queryParts = urlquery[i].split('=');
					if (queryParts[0] == 'lerr'){
						iserr = true;
						window.location = "/"+bandId;
					}
				}
			}
	
			if (iserr == false){
				window.location = "#"+pageStack[pageStack.length - 1]['target'];
			}
		}
	}catch(e){
		errorLog(['previous',e.message,false]);
	}
}

function adjustBackButton(){
	try{
		modif = 2;
		if(pageStack[(pageStack.length - 2)] == undefined){
			modif = 1;
		}
		if (isWebOS){
			setTimeout('backButtonText("'+pageStack[(pageStack.length - modif)]['itemName']+'")',500);
		}else{
			backButtonText(pageStack[(pageStack.length - modif)]['itemName']);
		}
	}catch(e){
		errorLog(['adjustBackButton',e.message,false]);
	}
}

function backButtonText(invar){
	try{
		document.getElementById('backBar_display').innerHTML = invar;
	}catch(e){
		errorLog(['backButtonText',e.message,false]);
	}
}


function pageDump(inPageStack){
	var ummstr = '';
	for (i in inPageStack){
		ummstr += i+": "+inPageStack[i]['command']+" "+inPageStack[i]['target']+" "+inPageStack[i]['itemName']+"<br>\n";
	}
	return ummstr+"<br>\n"+inPageStack.length;
}

var outPage = null;
var inPage = null;
function pageTransitionAnimeCallback() {
	try{
		inPage.removeEventListener('webkitAnimationEnd',pageTransitionAnimeCallback,false);
		outPage.removeEventListener('webkitAnimationEnd',pageTransitionAnimeCallback,false);
		
		window.scrollTo(0, 0);
		
		outPage.style.display = "none";
		
		removeClass(outPage,"slide_left");
		removeClass(outPage,"slide_left_reverse");
		removeClass(outPage,"slide_right");
		removeClass(outPage,"slide_right_reverse");
		
		removeClass(inPage,"slide_left");
		removeClass(inPage,"slide_left_reverse");
		removeClass(inPage,"slide_right");
		removeClass(inPage,"slide_right_reverse");
		
		if (pageStack.length > 1){
			document.getElementById('backBar').style.display = "block";
		}else{
			document.getElementById('backBar').style.display = "none";
		}
		
		runIntervals();
	}catch(e){
		errorLog(['pageTransitionAnimeCallback',e.message,false]);
	}
}

function pageAnimation(newPage,oldPage,animation,direction) {
	try{
		inPage = newPage;
		outPage = oldPage;	
		
		newPage.addEventListener('webkitAnimationEnd',pageTransitionAnimeCallback,false);
		
		addClass((direction == 1 ? oldPage : newPage ),animation+"_left"+(direction != 1 ? "_reverse" : ''));
		addClass((direction == 1 ? newPage : oldPage ),animation+"_right"+(direction != 1 ? "_reverse" : ''));
		
		inPage.style.display = "block";
	}catch(e){
		errorLog(['pageAnimation',e.message,false]);
	}
}

var commandInterval;
function tabBarMover() {
	try{
		if(inPage == undefined && inPage == null) {
			inPage = document.getElementById("homediv"); 
		}
		contentheight = inPage.offsetHeight+inPage.offsetTop;
	
		
		var commandParts = document.getElementById('currentCommand').value.split('/');
		var possibleDataSub = 'dataset_sub_'+commandParts[3]+'_'+commandParts[4];
		if (document.getElementById(possibleDataSub)){
			for(var i = 0; i < document.getElementById(possibleDataSub).childNodes.length; ++i ) {//>
				 contentheight = contentheight + (document.getElementById(possibleDataSub).childNodes[i].style.display == "block" ? document.getElementById(possibleDataSub).childNodes[i].offsetHeight : 0);
			}
		}
		
		if (contentheight < 300){ //>
			contentheight = 300;
		}
		document.getElementById("tabSpacer").style.height = (contentheight + 13)+'px';
	}catch(e){
		errorLog(['tabBarMover',e.message,false]);
	}
	
}

function webAppPageLoad(){
	runIntervals();
}

function runIntervals(){
	commandInterval = setInterval(function() {
    	tabBarMover();
    	checkLocation();
    }, 100);
};


var localStylesArray = new Array();
function pageTransition(page,direction){
	try{
		clearInterval(commandInterval);
		if (direction == 1){		
			if (localStylesArray[pageStack[(pageStack.length - 2)]['target']] == undefined){
				localStylesArray[pageStack[(pageStack.length - 2)]['target']] = document.getElementById(pageStack[(pageStack.length - 2)]['target']).firstChild.innerHTML;
			}
			
			document.getElementById(pageStack[(pageStack.length - 2)]['target']).firstChild.innerHTML = '';
			
			if (localStylesArray[page] != undefined ){
				document.getElementById(page).firstChild.innerHTML = localStylesArray[page];
			}
			
			leftPage = document.getElementById(pageStack[(pageStack.length - 2)]['target']);
			rightPage = document.getElementById(page);
							
			if(supportAnimation) {
				pageAnimation(rightPage,leftPage,"slide",direction);
			} else {
				inPage = document.getElementById(page);
				document.getElementById(pageStack[(pageStack.length - 2)]['target']).style.display = "none";
				document.getElementById(page).style.display = "block";
			}
		} else {
			if (localStylesArray[page] == undefined){
				localStylesArray[page] = document.getElementById(page).firstChild.innerHTML;
			}
			document.getElementById(page).firstChild.innerHTML = '';
			if (localStylesArray[pageStack[(pageStack.length - 1)]['target']] != undefined){
				document.getElementById(pageStack[(pageStack.length - 1)]['target']).firstChild.innerHTML = localStylesArray[pageStack[(pageStack.length - 1)]['target']];
			}	
			
			leftPage = document.getElementById(pageStack[(pageStack.length - 1)]['target']);
			rightPage =  document.getElementById(page);
			
			if(supportAnimation) {
				pageAnimation(leftPage,rightPage,"slide",direction);
			} else {
				inPage = document.getElementById(pageStack[(pageStack.length - 1)]['target']);
				document.getElementById(page).style.display = "none";
				document.getElementById(pageStack[(pageStack.length - 1)]['target']).style.display = "block";
			}
		}
		
		if(!supportAnimation) runIntervals();
		
		if (pageStack.length > 1){
			document.getElementById('backBar').style.display = "block";
		}else{
			if(direction == 1 || supportAnimation == false) document.getElementById('backBar').style.display = "none";
			if(agent == 'Custombandapp') window.location.href = '#deselectTab';
		}
		
		activityIndicator(0);	
	
		if (skipStackBool == 1){
			skipStack();
			skipStackBool = 0;
		}
		
		if (clearStackBool == 1){
			clearStack();
			clearStackBool = 0;
		}
	}catch(e){
		errorLog(['pageTransition',e.message,false]);
	}
}

var clearStackBool = 0;
function clearStack(){
	try{
		var newStack = new Array();
		newStack[0] = pageStack[0];
		newStack[1] = pageStack[pageStack.length - 1];
		pageStack = newStack;
	}catch(e){
		errorLog(['clearStack',e.message,false]);
	}
}

var skipStackBool = 0;
function skipStack(){
	try{
		pageStack.splice(pageStack.length - 2,1);
	}catch(e){
		errorLog(['skipStack',e.message,false]);
	}
}

function tabBarAction(tabId){
	try{
		if (actions[tabId]['action'].substr(0,1) != "/"){
			var possibleWebLink = actions[tabId]['action'].substr(0,4);
			if (possibleWebLink == "http" || possibleWebLink == "maps" || possibleWebLink == "tel:"){
				window.location.href = actions[tabId]['action'];
			}else if (actions[tabId]['action'].substr(0,7) == "SPECIAL"){
				specialAction(actions[tabId]['action']);
			}else if (actions[tabId]['action'].substr(0,11) == "javascript:"){
				eval(actions[tabId]['action']);
			}else{
				window.location.href = '#' + actions[tabId]['action'];
			}
		}else{
			closeMap();
			closeEmailWindow();
			closeContatList();
			if (actions[tabId]['action'] == "/home"){
				loadHome();
			} else if (pageStack[pageStack.length - 1]['command'] != actions[tabId]['action']){
				clearStackBool = 1;
				doRequest(actions[tabId]['action'],actions[tabId]['name']);
			}
			resetSearch();
		}
	}catch(e){
		errorLog(['tabBarAction',e.message,false]);
	}
	
}

function specialAction(action){
	try{
		var actionCommand = action.split(":");
		var current = document.getElementById('currentCommand').value.split("/");
		if (actionCommand[1] == "nextNewsItem"){
			if (document.getElementById('nextNewsCommand_'+current[current.length - 1])){
				var command = document.getElementById('nextNewsCommand_'+current[current.length - 1]).value;
				skipStackBool = 1;
				doRequest(command);
			}
		}
		if (actionCommand[1] == "prevNewsItem"){
			if (document.getElementById('prevNewsCommand_'+current[current.length - 1])){
				var command = document.getElementById('prevNewsCommand_'+current[current.length - 1]).value;
				skipStackBool = 1;
				doRequest(command);
			}
		}
	}catch(e){
		errorLog(['specialAction',e.message,false]);
	}
}

function resetLinks(){
	window.location.href = '#';
}

function checkLocation(){
	if(agent != 'Custombandapp' && isWebOS != true){
		revisitLocation();
	}
}

function loadHome(){
	if (pageStack.length > 1){
		clearStack();
		previous();
	}
}

function revisitLocation(){
	try{
		if(window.location.hash == '') {
			window.location.hash = 'homediv';
		}
		if (pageStack[pageStack.length - 1] != undefined && '#'+pageStack[pageStack.length - 1]['target'] != location.hash){
			var stackRebuild = new Array();
			var reached = 0;
			for (i=0; i< pageStack.length; ++i){ ///>
				stackRebuild[i] = new Array();
				stackRebuild[i]['command'] = pageStack[i]['command'];
				stackRebuild[i]['target'] = pageStack[i]['target'];
				stackRebuild[i]['itemName'] = pageStack[i]['itemName'];
				if (('#'+pageStack[i]['target']) == location.hash){
					var currentTarget = pageStack[i]['target'];
					stackRebuild[i+1] = new Array();
					stackRebuild[i+1]['command'] = pageStack[i+1]['command'];
					stackRebuild[i+1]['target'] = pageStack[i+1]['target'];
					stackRebuild[i+1]['itemName'] = pageStack[i+1]['itemName'];
					reached = 1;
					break;
				}
			}
			pageStack = stackRebuild;
			if (reached == 0){
				newLoaction = location.hash.replace(/#/g,'');				if(document.getElementById('gapage') != null) {;
				var gapagevalue = document.getElementById('gapage').value;	
				
		 		//_gaq.push(['_setAccount','<?= (strlen($googleAnalyticsCode) > 0) ? $googleAnalyticsCode : 'UA-9264241-3'; ?>']);
		 		_gaq.push(['_trackPageview',gapagevalue]);
	
				if(hasMoonTracker) {
					//_gaq.push(['b._setAccount','<?= $googleAnalyticsCodeMoon ?>']);
					_gaq.push(['b._trackPageview',gapagevalue]);					
				}
			}
				doRequest(newLoaction.replace(/_/g,'/'));
			}else{
				previous();
			}		
		}
	}catch(e){
		errorLog(['revisitLocation',e.message,false]);
	}
}

function versionInfoRequest(type){
	switch (type) {
		case 0:
		case "av":
			return server_av;
			break;
		case 1:
		case "sv":
			return server_sv;
			break;
	}
}

function isLoaded(){
	return "1";
}

function updatedSiteInfoKeys(version){
	try{
		var returnString = '';
		i = 0;
		for (var x in siteVersionInfo[version]){
			if (i != 0){
				returnString += ',';
			}
			returnString += x;
			++i;
		}
		return returnString;
	}catch(e){
		errorLog(['updatedSiteInfoKeys',e.message,false]);
	}
}

function updatedSiteInfoVals(version){
	try{
		var keysString = updatedSiteInfoKeys(version);
		var keyArray = keysString.split(',');
		var returnString = '';
		i = 0;
		for (var x in keyArray){
			if (i != 0){
				returnString += ',';
			}
			returnString += siteVersionInfo[version][keyArray[x]];
			++i;
		}
		return returnString;
	}catch(e){
		errorLog(['updatedSiteInfoVals',e.message,false]);
	}
}

var trackStarted = 0;
function startStream(trackId){
	try{
		for (var i in streamIds){
			if (streamIds[i] == trackId){
				if (agent == 'Custombandapp'){
					window.location.href = "#playTrack:"+i;
					window.location.href = "#";
				}else{
					if (trackStarted != streamIds[i]){
						document.getElementById('player_frame').src = "";
						document.getElementById('player_frame').src = getTrackById(i);
						document.getElementById('speakerIcon_'+streamIds[i]).src = contentServer + "/images/speakerAnim.gif";
						if (trackStarted > 0){
							document.getElementById('speakerIcon_'+trackStarted).src = contentServer + "/images/speakerIcon.gif";
						}
						trackStarted = streamIds[i];
					}else{
						document.getElementById('player_frame').src = "";
						document.getElementById('speakerIcon_'+streamIds[i]).src = contentServer + "/images/speakerIcon.gif";
						trackStarted = 0;
					}
				}
			}
		}
	}catch(e){
		errorLog(['startStream',e.message,false]);
	}
}

function activityIndicator(onOff){
	try{
		if (onOff == 0){
			if(agent == 'Custombandapp'){
				window.location.href = '#';
				window.location.href = '#actOff';
			} else {		
				document.getElementById('activity_indicator').style.display = "none";
			}
		}
		if (onOff == 1){
			if(agent == 'Custombandapp'){
				window.location.href = '#';
				window.location.href = '#actOn';
			} else {		
				document.getElementById('activity_indicator').style.display = "block";
			}
		}
	}catch(e){
		errorLog(['activityIndicator',e.message,false]);
	}
}

var isFromPrefilteredList = false;
var preFilteredListId = 0;
var openListId = 0;
var voterCountForList = 0;
var nameForList = 'Walking List';
var dataset_designator_type;
var currentPage = 0;
function viewListById(listId,dataset,featureId,page,voterCount,listName){
	isFromPrefilteredList = true;
	preFilteredListId = listId;
	openListId = listId;
	voterCountForList = voterCount;
	nameForList = listName;
	currentPage = page;
	performDatasetSearch(dataset,featureId,page);
}


function performDatasetSearch(dataset,featureId,page) {
	try{
		if(!performFormValidation(dataset,featureId)) {
			return false;
		}
		currentPage = page;
		activityIndicator(1);
		
		var params = "";
		
		//Search values
		var location = "";
		if (document.getElementById(dataset+'_'+featureId+'_location')){
			location = document.getElementById(dataset+'_'+featureId+'_location').value;
			state = document.getElementById(dataset+'_'+featureId+'_location_state').options[document.getElementById(dataset+'_'+featureId+'_location_state').selectedIndex].value;
			
			if(document.getElementById(dataset+'_'+featureId+'_near_geo').style.display == "inline") {
				location = "Current Location";
			}else if(location == document.getElementById(dataset+'_'+featureId+'_location').title){
				location = "";
			}
			
			if(location !== undefined) 	params += "&location="+location;
			if(state !== undefined) 	params += "&state="+state;
		} 
		
		if(document.getElementById('dataset_designator_'+featureId+'_data_ids') != null && document.getElementById('dataset_designator_'+featureId+'_data_ids').value != "") {
			var idDataExploded = document.getElementById('dataset_designator_'+featureId+'_data_ids').value.split(",");	
			var idMappingExploded = document.getElementById('dataset_designator_'+featureId+'_data_mappings').value.split(",");
			
			for(var i in idDataExploded) {
				if(document.getElementById(idDataExploded[i]) != undefined) params += "&"+idMappingExploded[i]+"="+document.getElementById(idDataExploded[i]).value;
			}
		}	
		
		params += "&geo_y="+lat;
		params += "&geo_x="+lon;
		
		var distance = 0
		if(document.getElementById(dataset+'_'+featureId+'_distance')){
			distance = document.getElementById(dataset+'_'+featureId+'_distance').value;
			params += "&distance="+distance;
		}
		var when = "All";
		if(document.getElementById(dataset+'_'+featureId+'_when') != undefined) {
			when = document.getElementById(dataset+'_'+featureId+'_when').value;
			params += "&when="+when;
		}
		
		var eventAjaxObject;
		
		if (!(eventAjaxObject = new ajaxObj())){
			errorLog(['performDatasetSearch','ajaxObject failed',false]);
		}
		
		var rightnow = new Date();
		
		var postString = '/dataset/items/'+featureId+'/'+page+'?ts='+rightnow.getTime();
		if (isFromPrefilteredList && userId > 0){
			postString = '/dataset/preFilteredItems/'+featureId+'/'+page+'/'+userId+'/'+preFilteredListId+'/'+voterCountForList+'?ts='+rightnow.getTime();
			if (document.getElementById(dataset+'_'+featureId+'_hfv')){
				params += "&hfv="+(document.getElementById(dataset+'_'+featureId+'_hfv').checked ? 1 : 0);
			}
			if (document.getElementById(dataset+'_'+featureId+'_hpv')){
				params += "&hpv="+(document.getElementById(dataset+'_'+featureId+'_hpv').checked ? 1 : 0);
			}
			params += "&hnv="+((document.getElementById(dataset+'_'+featureId+'_hnv') && document.getElementById(dataset+'_'+featureId+'_hnv').checked) ? 1 : 0);
			params += "&sort="+(document.getElementById(dataset+'_'+featureId+'_sort_method') ? document.getElementById(dataset+'_'+featureId+'_sort_method').options[document.getElementById(dataset+'_'+featureId+'_sort_method').selectedIndex].value : 'zig_zag');
			params += "&listName="+nameForList;
		}
		
		eventAjaxObject.open('POST',postString,true);
		
		eventAjaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		
		eventAjaxObject.onreadystatechange = function(){
			if (eventAjaxObject && eventAjaxObject.readyState == 4 && eventAjaxObject.status == 200){
				try {
					var oldgapage = document.getElementById('gapage');
					if(oldgapage != null) {
						oldgapage.parentNode.removeChild(oldgapage);
					}				
						
					if (eventAjaxObject.responseText != "NULL") {
						
						try{
							var response = JSON.parse(eventAjaxObject.responseText)
							if (response.success == 0 && response.result == 'logout'){
								logoutAction();
								return false;
							}
							if (response.success == 0 && response.result == 'socketError'){
								socketErrAction();
								return false;
							}
						}
						catch(e){
							//fail; continue
						}
						
						var oldgapage = document.getElementById('gapage');
						if(oldgapage != null) {
							oldgapage.parentNode.removeChild(oldgapage);
						}				
						
						document.getElementById(dataset+'_'+featureId+'_results_div').style.display = "none";
						document.getElementById(dataset+'_'+featureId+'_results_div').innerHTML = eventAjaxObject.responseText;
						
						document.getElementById(dataset+'_'+featureId+'_no_result_message').style.display = "none";
						
						if (isFromPrefilteredList && userId > 0){
							createSettings(dataset+'_'+featureId+'_walkinglist_options','divcon');
							isFromPrefilteredList = false;
						}
						
						if(supportAnimation) {
							var leftPage = document.getElementById(dataset+'_'+featureId+'_search_div');					
							var rightPage = document.getElementById(dataset+'_'+featureId+'_results_div');
							pageAnimation(rightPage,leftPage,"slide",1);					
						} else {
							document.getElementById(dataset+'_'+featureId+'_search_div').style.display = "none";
							document.getElementById(dataset+'_'+featureId+'_results_div').style.display = "block";
						}
						
						if(document.getElementById('gapage') != null) {;
							var gapagevalue = document.getElementById('gapage').value;	
							
					 		//_gaq.push(['_setAccount','<?= (strlen($googleAnalyticsCode) > 0) ? $googleAnalyticsCode : 'UA-9264241-3'; ?>']);
					 		_gaq.push(['_trackPageview',gapagevalue]);
		
							if(hasMoonTracker) {
								//_gaq.push(['b._setAccount','<?= $googleAnalyticsCodeMoon ?>']);
								_gaq.push(['b._trackPageview',gapagevalue]);					
							}					
						}
		
					} else {
						document.getElementById(dataset+'_'+featureId+'_no_result_message').style.display = "block";
						isFromPrefilteredList = false;
						resetSearch();
					}
					
					activityIndicator(0);
					
					if (openMapBool){
						openMap(dataset,featureId);
						openMapBool = false;
					}
					
					window.scrollTo(0,0);
				}catch(e){
					alert(e.message);
				}
			}
		}
		
		eventAjaxObject.send(params);
	}catch(e){
		errorLog(['performDatasetSearch',e.message,false]);
	}
}

function nextSearchItem(direction,designator,featureId,id){ //direction: -1 = back, 1 = frwrd
	try{
		if (notSaved){
			if(confirm("Changes have not been saved!")){
				notSaved = false;
			}else{
				return;
			}
		}
		if(document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_all_ids')) {
			var idsArray = document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_all_ids').value.split(',');
			var nextId;
			for(var i = 0; i < idsArray.length; ++i){ //>
				if (idsArray[i] == id){
					var newId = i + direction;
					if (newId > idsArray.length - 1){
						newId = 0;
						
					}else if (newId < 0){  //>
						newId = idsArray.length - 1;
						
					}
					nextId = idsArray[newId];
					
					if (isWalkinglists()){
						var perPage = document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_itemsPerPage').value;				
						currentPage = Math.floor(newId / perPage); 
					}
					
					showDatasetDetails(designator,featureId,nextId,(direction == 1 ? 1 : 0));
					break;
				}
			}
		}
	}catch(e){
		errorLog(['nextSearchItem',e.message,false]);
	}
}

function resetSearch(){
	try{
		if (document.getElementById('search_div')){
			document.getElementById('details_div').style.display = "none";
			
			if(supportAnimation) {
				var leftPage = document.getElementById('search_div').style.display;					
				var rightPage = document.getElementById('results_div').style.display;
				pageAnimation(rightPage,leftPage,"slide",0);					
			} else {
				document.getElementById('results_div').style.display = "none";
				document.getElementById('search_div').style.display = "block";
			}
		}
	}catch(e){
		errorLog(['resetSearch',e.message,false]);
	}
}

function performFormValidation(dataset,featureId) {
	try{
		var requiredExploded = document.getElementById('dataset_designator_'+featureId+'_required_ids').value.split(",");	
		var requiredMappingExploded = document.getElementById('dataset_designator_'+featureId+'_required_mappings').value.split(",");	
		var requiredDefaults = document.getElementById('dataset_designator_'+featureId+'_required_defaults').value.split(",");	
		
		var missingField = new Array();
		
		var j = 0;
		for(var i in requiredExploded) {
			var elem = document.getElementById(requiredExploded[i]);
					
			if(elem != undefined && elem.disabled != true) {
				if(elem.value == 0) {
					missingField[j] = requiredMappingExploded[i];
					++j;
				}else if(elem.value == "") {
					missingField[j] = requiredMappingExploded[i];
					++j;
				}else if(elem.value == requiredDefaults[i]) {
					missingField[j] = requiredMappingExploded[i];
					++j;
				}
			}
		}
		
		if(missingField.length > 0) {
			var missingString = '';
			for(i = 0; i < missingField.length; ++i){ //>
				missingString += '<br>' + '   '+missingField[i];
			}
			popAlert("The following fields are required:" + missingString, 'missingFieldsElem');
			return false;
		}
		
		return true;
	}catch(e){
		errorLog(['performFormValidation',e.message,false]);
	}
}


function clearDefault(elem){
	if (elem.value == ""){
		elem.style.color = "gray";
		elem.value = elem.title
	}else if (elem.value == elem.title){
		elem.value = "";
		elem.style.color = "black";
	}
}

function closeMap(){
	currentMapFeatureId = null;
	currentMapDataset = null;
	if(agent == 'Custombandapp'){
		window.location.href = '#closeMap';
	}
}

var currentMapFeatureId = null;
var currentMapDataset = null;
function openMap(dataset,featureId){
	try{
		currentMapFeatureId = featureId;
		currentMapDataset = dataset;
		if(agent == 'Custombandapp'){
			window.location.href = "#showMap";
		} else {
			if(document.getElementById("momoMapDiv") == null) {
				createMoboMap();
			} else {
				openMoboMap(false);	
			}		
		}
			
		document.getElementById('divcon').style.visibility = "visible";
	}catch(e){
		errorLog(['openMap',e.message,false]);
	}
}

var map = null;
function createMoboMap() {
	try{
		var mapDiv = document.createElement('div');
		mapDiv.style.display = "none";
		mapDiv.id = "momoMapDiv";
		
		var useragent = navigator.userAgent;
		if (useragent.indexOf('iPhone') != -1) {
			mapDiv.style.display = "block";
			mapDiv.style.width = window.innerWidth+"px";
			mapDiv.style.height = window.innerHeight+"px";
		} else {
			var clientHeight = document.documentElement.clientHeight;
			mapDiv.style.height = clientHeight+"px";
			var clientWidth = document.documentElement.clientWidth;
			mapDiv.style.width = clientWidth+"px";
		}	
		
		document.getElementById("body").appendChild(mapDiv);
	
		if (useragent.indexOf('iPhone') != -1) {
			window.scrollTo(0, 1);
		}
		
		var latLng = new google.maps.LatLng(startLat(),startLong());
		var myOptions = {
			draggable: true,
			noClear: true,
			zoom: 16,
			center: latLng,
		    mapTypeControl: true,
		    mapTypeControlOptions: {position: google.maps.ControlPosition.TOP_RIGHT, mapTypeIds: [google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.HYBRID,google.maps.MapTypeId.TERRAIN],style: google.maps.MapTypeControlStyle.HORIZONTAL_MENU},
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			navigationControl: true,
			navigationControlOptions: {style:google.maps.NavigationControlStyle.ZOOM_PAN}
		};	
		
		map = new google.maps.Map(document.getElementById("momoMapDiv"), myOptions);
		buildMapControls();
		openMoboMap(true);
	}catch(e){
		errorLog(['createMoboMap',e.message,false]);
	}
}

function buildMapControls() {
	try{
		var closeDiv = document.createElement('div');
		closeDiv.style.padding = '5px';
		
		var buttonImg = document.createElement('img');
		buttonImg.src = contentServer+"/images/closeButton.png";
		
		google.maps.event.addDomListener(closeDiv, 'click', function() {
			closeMoboMap();
		});
		
		closeDiv.appendChild(buttonImg);
		
		map.controls[google.maps.ControlPosition.BOTTOM].push(closeDiv);
	}catch(e){
		errorLog(['buildMapControls',e.message,false]);
	}
}

var currentWidth;
var currentHeight;
var updateLayout;
var panStartPos = false;
function openMoboMap(firstOpen) {
	try{
		map.clearMarkers();
		
		var mBounds = new google.maps.LatLngBounds();
		
		var lists = returnEventIds();
		lists = lists.split(',');	
		
		if(detailsShowing()) {
			if(document.getElementById(currentMapDataset+"_"+currentMapFeatureId+"_details_id") != null) {
				var c = parseInt(document.getElementById(currentMapDataset+"_"+currentMapFeatureId+"_details_id").value);
				lists.push(c);
			}
		}
		
		document.getElementById("body").style.paddingBottom = "0px";
		document.getElementById("maincon").style.display = "none";
		if (document.getElementById("adsdiv")) document.getElementById("adsdiv").style.display = "none";
		document.getElementById("momoMapDiv").style.display = "block";	
		
		for(var v in lists) {
			var n = lists[v];
			if(appType == 'groundgame'){
				var d = JSON.parse(returnLocationsDataV2(parseInt(n)));
			} else {
				var d = {};
				d.id = n;
				d.pin = "pinGreen";
				d.title = document.getElementById(currentMapDataset+"_name_"+n).innerHTML;
				d.latitude = parseFloat(document.getElementById(currentMapDataset+"_lat_"+n).value);
				d.longitude = parseFloat(document.getElementById(currentMapDataset+"_long_"+n).value);
			}
			
			var l = new google.maps.LatLng(parseFloat(d.latitude),parseFloat(d.longitude));
			mBounds.extend(l);
			
			var hex = "FFFF00";
			var character = "U";
			switch(d.pin) {
				case 'pinRed':
					hex = "FF0000";
					character = "R";
					break;
				case 'pinBlue':
					hex = "0000FF";
					character = "D";
					break;
				case 'pinGray':
					hex = "FFFF00";
					character = "U";
					break;
				case 'pinGreen':
					hex = "228B22";					
					break;
				case 'pinRainbow':
					hex = "AAAAAA";
					character = "M";
					break;
			}
			
			var characterString = "&c="+character;
			if(appType != 'groundgame'){
				characterString = '';
			}
			
			var img = new google.maps.MarkerImage(domain+"/scripts/marker.php?h="+hex+characterString,
				new google.maps.Size(20,34),
				new google.maps.Point(0,0),
				new google.maps.Point(10,34)
			);
			
			var m = new google.maps.Marker({
		        position: l,
		        map: map,
		        boolean: true,
		        icon: img,	
		        flat: true
		    });		
			
		    google.maps.event.addListener(m,'click', function() {	    	
		    	openInfoWindow(this);
		    });			
		    
		    var infoContainer = document.createElement("div");
		    infoContainer.v_id = n;
		    infoContainer.title = d.title;

		    infoContainer.style.fontSize = "10pt";
		    
		    var titleContainer =  document.createElement("div");		   
		    titleContainer.innerHTML = d.title;
		    titleContainer.style.textDecoration = "underline";
		    titleContainer.style.fontWeight = "bold";
		    infoContainer.appendChild(titleContainer);
		    
		    if(d.subtitle == "" || d.subtile == undefined) {
		    	d.subtitle = "Tap for details";
		    }
		    
		    if(d.subtitle != "") {
		    	var subContainer = document.createElement("div");
		    	subContainer.appendChild(document.createTextNode(d.subtitle));
		    	subContainer.style.fontSize = "8pt";
		    	infoContainer.appendChild(subContainer);
		    }
		    
		    google.maps.event.addDomListener(infoContainer,'click', function() {
	    		showDatasetDetails(currentMapDataset,currentMapFeatureId,this.v_id,1);
		    });
			
			m.infoWindowContent = infoContainer;
		    m.v_id = n;
		}
		
		google.maps.event.trigger(map,'resize');
		
		var centerMap = function () {	
			map.setCenter(new google.maps.LatLng(startLat(),startLong()));
			if(!detailsShowing()) map.fitBounds(mBounds);
		}
		
		setTimeout(centerMap,500);
		
		updateLayout = function() {
			if (window.innerWidth != currentWidth || window.innerHeight != currentHeight) {
				document.getElementById("momoMapDiv").style.width = window.innerWidth+"px";
				document.getElementById("momoMapDiv").style.height = window.innerHeight+"px";
				currentWidth = window.innerWidth;
				currentHeight = window.innerHeight;
				google.maps.event.trigger(map,'resize');
			}
		};
		setInterval(updateLayout, 500);	
	}catch(e){
		errorLog(['openMoboMap',e.message,false]);
	}
}

var infoWindow = false;
function openInfoWindow(marker) {
	if(infoWindow != false) {
		infoWindow.close();		
	} 
		
	if(infoWindow == false) {
		infoWindow = new google.maps.InfoWindow({
			content: marker.infoWindowContent,
			maxWidth: '200'
		});
		
		infoWindow.v_id = marker.v_id;
		    
	    google.maps.event.addListener(map,'click', function() {	  
	    	if(infoWindow != false) {
	    		infoWindow.close();
	    	}	    	
	    });
	    
	    google.maps.event.addListener(map,'drag', function() {	    	
	    	if(infoWindow != false) {
	    		infoWindow.close();
	    	}
	    });
	    
	    google.maps.event.addListener(map,'dblclick', function() {	    	
	    	if(infoWindow != false) {
	    		infoWindow.close();
	    	}
	    });
	} else {
		infoWindow.setContent(marker.infoWindowContent);
	}
	    
    infoWindow.open(map,marker);	
}


function closeMoboMap() {
	try{
    	if(infoWindow != false) {
    		infoWindow.close();
    	}		
		
		clearInterval(updateLayout);
		document.getElementById("body").style.paddingBottom = "40px";
		document.getElementById("maincon").style.display = "block";
		if (document.getElementById("adsdiv")) document.getElementById("adsdiv").style.display = "block";
		document.getElementById("momoMapDiv").style.display = "none";
	}catch(e){
		errorLog(['closeMoboMap',e.message,false]);
	}
}

var openMapBool = false;
function defaultSearchFromMap(dataset,featureId){
	try{
		if(agent == 'Custombandapp'){
			if (currentMapDataset == null || currentMapFeatureId == null || !returnEventIds() ){
				if (currentMapFeatureId == null){
					currentMapFeatureId = featureId;
				}
				if (currentMapDataset == null){
					currentMapDataset = dataset;
				}
				doRequest('/dataset/index/'+currentMapFeatureId+'/'+bandId,'Open Map');
				document.getElementById('divcon').style.visibility = "hidden";
				performDatasetSearch(currentMapDataset,currentMapFeatureId,0);
				openMapBool = true;
			}else{
				window.location.href = "#showMap";
			}
		}
	}catch(e){
		errorLog(['defaultSearchFromMap',e.message,false]);
	}
}

function isWalkinglists(){
	try{
		return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_dataset_designator_type') && document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_dataset_designator_type').value == "walkinglists";
	}catch(e){
		errorLog(['isWalkinglists',e.message,false]);
	}
}

function returnEventIds() {
	try{
		if (detailsShowing()) {
			if (isWalkinglists()){
				return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_all_ids_jump').value;
			}		
			return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_details_id').value;
		} else if(document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_all_ids')) {
			var allIds = document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_all_ids').value.split(',');
			var perPage = document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_itemsPerPage').value;
			var newIdString = '';
			for(var i = (currentPage * perPage); i < ((currentPage * perPage) + (perPage - 1)) ; ++i){ //>
				if (allIds[i]){
					if (newIdString != '') {
						newIdString += ',';
					}
					newIdString += allIds[i];
				}else{
					break;
				}
			}
			return newIdString;
		}else{
			return false;
		}
	}catch(e){
		errorLog(['returnEventIds',e.message,false]);
	}
}

function getHidePinOptions(){
	try{
		var hideVal = 0;
		hideVal += document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_hfv') && document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_hfv').checked ? 100 : 0;
		hideVal += document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_hpv') && document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_hpv').checked ? 10 : 0;
		hideVal += document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_hnv') && document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_hnv').checked ? 1 : 0;
		return hideVal;
	}catch(e){
		errorLog(['getHidePinOptions',e.message,false]);
	}		
}

function detailsShowing(){
	try{
		var showing = false;
		if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_details_div') != undefined){
			if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_details_div').style.display == "block"){
				showing = true;
			}
			if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_details_div').style.display == "none"){
				showing = false;
			}
		}
		
		return showing;
	}catch(e){
		errorLog(['detailsShowing',e.message,false]);
	}		
}

function saveLanguage(langIndex){
	window.location.href = "#prefs:language:"+langIndex;
}

function saveLocation(zip) {
	window.location.href = "#prefs:location:"+zip;
}

function saveLat(inLat) {
	window.location.href = "#prefs:lat:"+inLat;
}

function saveLon(inLong) {
	window.location.href = "#prefs:lon:"+inLong;
}

function setLat(val){
	lat = val;
	document.cookie = "lat=" + val;
}

function setLong(val){
	lon = val; 
	document.cookie = "lon=" + val;
}

function restorePrefs(){
	window.location.href = '#resetPrefs';
}

function getDirections(dataset,featureId) {
	try{
		currentMapFeatureId = featureId;
		currentMapDataset = dataset;
		if(startLat() == 0 || startLong() == 0) {
			var startLoc = "";
		} else {
			var startLoc = startLat()+","+startLong();
		}
		var endLoc = document.getElementById(dataset+'_'+currentMapFeatureId+'_venue_lat').value+","+document.getElementById(dataset+'_'+currentMapFeatureId+'_venue_long').value;
		if (confirm("Close your application and open Google maps?")){
			window.location.href = "http://maps.google.com/maps?saddr="+startLoc+"&daddr="+endLoc+"#extURL";
		}
	}catch(e){
		errorLog(['getDirections',e.message,false]);
	}	
}

function startLat(){
	try{
		if (detailsShowing()){
			if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_venue_lat')){
				return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_venue_lat').value;
			}
		}
		if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_results_lat')){
			return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_results_lat').value;
		}
	}catch(e){
		errorLog(['startLat',e.message,false]);
	}
}

function startLong(){
	try{
		if (detailsShowing()){
			if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_venue_long')){
				return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_venue_long').value;
			}
		}
		if (document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_results_long')){
			return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_results_long').value;
		}
		
		
	}catch(e){
		errorLog(['startLong',e.message,false]);
	}
}

function returnLocationsData(id){
	try{
		var event_name = document.getElementById(currentMapDataset+'_name_'+id).innerHTML;
		var event_sub = "";
		var event_lat = document.getElementById(currentMapDataset+'_lat_'+id).value;
		var event_long = document.getElementById(currentMapDataset+'_long_'+id).value;
		return event_name + "#STRINGDELIM#" + event_sub + "#STRINGDELIM#" + event_lat + "#STRINGDELIM#" + event_long + "#STRINGDELIM#" + id;
	}catch(e){
		errorLog(['returnLocationsData',e.message,false]);
	}
}

function returnLocationsDataV2(id) {
	try{
		var locData = new Object();
		locData.id = id;
		var detailsShown = detailsShowing();
		if (document.getElementById(currentMapDataset+'_name_'+id)){			
			locData.title = document.getElementById(currentMapDataset+'_name_'+id).innerHTML;
			locData.subtitle = document.getElementById(currentMapDataset+'_sub_'+id).value;
			locData.latitude = document.getElementById(currentMapDataset+'_lat_'+id).value;
			locData.longitude = document.getElementById(currentMapDataset+'_long_'+id).value;
			locData.pin = document.getElementById(currentMapDataset+'_pin_'+id).value;
			//locData.visited = document.getElementById(currentMapDataset+'_address_visited_'+id).value;
			if(isWalkinglists() && document.getElementById('jumpto_top') && detailsShown){
					locData.pin = 'pinYellow';
			}
			return JSON.stringify(locData);
			
		}else if(isWalkinglists() && document.getElementById('jumpto_top')){ 
			
			if (document.getElementById('jumpto_local_latlon_'+id)){
				locData.title = document.getElementById('jumpto_local_address_'+id).value;
				locData.subtitle = '';
				var latlong = document.getElementById('jumpto_local_latlon_'+id).value.split(',');
				locData.latitude = latlong[0];
				locData.longitude = latlong[1];
				locData.pin = 'pinYellow';
				//locData.visited = document.getElementById(currentMapDataset+'_address_visited_'+id).value;
				return JSON.stringify(locData);
			}else{
				locData.title = document.getElementById('jumpto_'+id).innerHTML;
				locData.subtitle = '';
				var latlong = document.getElementById('jumpto_'+id).title.split(',');
				locData.latitude = latlong[0];
				locData.longitude = latlong[1];
				locData.pin = 'pinYellow';
				//locData.visited = document.getElementById(currentMapDataset+'_address_visited_'+id).value;
				return JSON.stringify(locData);
			}
		}else if(dataset_designator_type == "quickbeamsearch"){
			locData.title = document.getElementById('name_'+id).innerHTML;
			locData.subtitle = '';
			locData.latitude = document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_venue_lat').value;
			locData.longitude = document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_venue_long').value;
			locData.pin = 'pinYellow';
			return JSON.stringify(locData);
		}
	}catch(e){
		errorLog(['returnLocationsDataV2',e.message,false]);
	}
}

function returnRadialDistance(){
	try{
		if (detailsShowing()){
			if(isWalkinglists()){
				return 0.07;
			}
			var datasetDetails = returnEventIds();
			if(startLat() == 0 || startLong() == 0) { 
				return 10;
			} else {
				return document.getElementById(currentMapDataset+'_'+datasetDetails+'_distance').value * 2;
			}
		} else {
			return document.getElementById(currentMapDataset+'_'+currentMapFeatureId+'_results_range').value * 1;
		}
	}catch(e){
		errorLog(['returnRadialDistance',e.message,false]);
	}
}

function showEventDetailsFromMap(id){
	showDatasetDetails(currentMapDataset,currentMapFeatureId,id,1);
}

function retrMessage(onOff){
	try{
		if (onOff){
			if (!document.getElementById('retrieveDataDiv')){
				var retr = document.createElement('div');
				retr.setAttribute('id','retrieveDataDiv');
				retr.setAttribute('style','display: block');
				retr.innerHTML = "Retrieving Data...";
				document.getElementById('divcon').appendChild(retr);
			}
		}
		if (!onOff){
			if (document.getElementById('retrieveDataDiv')){
				document.getElementById('retrieveDataDiv').style.display = "none";
				document.getElementById('divcon').removeChild(document.getElementById('retrieveDataDiv'));
			}
		}
	}catch(e){
		errorLog(['retrMessage',e.message,false]);
	}
}

function showDatasetDetails(dataset,featureId,eventId,direction) {
	
	try{
		
		if(document.getElementById("momoMapDiv") != null && document.getElementById("momoMapDiv").style.display == "block") {
			closeMoboMap();
		}
		if (eventId == '' || eventId == null || eventId == 0) return false;
		if (document.getElementById(dataset+'_'+featureId+'_dataset_designator_type')) {
			dataset_designator_type = document.getElementById(dataset+'_'+featureId+'_dataset_designator_type').value;
		}
		if (dataset_designator_type == "quickbeamsearch"){
			fromQBSearch=2;
			moveBackBar(1);
			document.getElementById('quickbeamsearch_row').style.display = "none";
			document.getElementById('qbResultsPane').style.display = "none";
		}
		activityIndicator(1);
			
		var eventAjaxObject;
		if(!(eventAjaxObject = new ajaxObj())){
			errorLog(['showDatasetDetails','ajaxObject failed',false]);
		}
		
		var currentLat = document.getElementById(dataset+'_'+featureId+'_results_lat') ? document.getElementById(dataset+'_'+featureId+'_results_lat').value : lat;
		var currentLong = document.getElementById(dataset+'_'+featureId+'_results_long') ? document.getElementById(dataset+'_'+featureId+'_results_long').value : lon;		
		
		var detailsQuery = '/dataset/details/'+featureId+'/'+eventId+'/'+currentLat+'/'+currentLong+'/'+dataset_designator_type
		if (dataset_designator_type == 'walkinglists'){
			currentLat = lat;
			currentLong = lon;
			if (document.getElementById(dataset+'_'+featureId+'_all_ids')){
				var allIds = document.getElementById(dataset+'_'+featureId+'_all_ids').value.split(',');
				var nextId = 0;
				var prevId = 0;
				for(var i = 0; i < allIds.length; ++i){ //>
					if (allIds[i] == eventId){
						var nextId = i <= (allIds.length - 2) ? allIds[i + 1] : 0; //>
						var prevId = i > 0 ? allIds[i - 1] : 0;
						break;
					}
				}
			}
			detailsQuery += '/'+openListId+'/'+getHidePinOptions()+'/'+nextId+'/'+prevId+'/'+eventId;
		}
		
		
		var rightnow = new Date();
		eventAjaxObject.open('GET',detailsQuery+'?ts='+rightnow.getTime(),true);
		
		eventAjaxObject.onreadystatechange = function(){
			try{
				if (eventAjaxObject && eventAjaxObject.readyState == 4 && eventAjaxObject.status == 200){
					var oldgapage = document.getElementById('gapage');
					if(oldgapage != null) {
						oldgapage.parentNode.removeChild(oldgapage);
					}	
					
					try{
						var response = JSON.parse(eventAjaxObject.responseText)
						if (response.success == 0 && response.result == 'logout'){
							logoutAction();
							return false;
						}
						if (response.success == 0 && response.result == 'socketError'){
							socketErrAction();
							return false;
						}
					}
					catch(e){
						//fail; continue
					}
					
					
					document.getElementById(dataset+'_'+featureId+'_details_div').innerHTML = eventAjaxObject.responseText;	
					
					if (fromQBSearch == 2){
						document.getElementById('paginationTop').style.display = "none";
						document.getElementById('paginationBottom').style.display = "none";
						document.getElementById('canvas_questions_'+eventId).style.display = "none";
						document.getElementById('eventDetails_'+featureId+'_'+eventId).className = document.getElementById('eventDetails_'+featureId+'_'+eventId).className + " qbResultsStyle";
						fromQBSearch = 1;
					}
					
					retrMessage(false);
					if (document.getElementById(dataset+'_'+featureId+'_search_back')) document.getElementById(dataset+'_'+featureId+'_search_back').style.display = "block";
					
					if(supportAnimation) {
						var rightPage = document.getElementById(dataset+'_'+featureId+'_details_div');					
						var leftPage = document.getElementById(dataset+'_'+featureId+'_results_div');
						pageAnimation(rightPage,leftPage,"slide",direction);			
					} else {				
						document.getElementById(dataset+'_'+featureId+'_results_div').style.display = "none";
						document.getElementById(dataset+'_'+featureId+'_details_div').style.display = "block";
					}
					
					if(document.getElementById('gapage') != null) {;
						var gapagevalue = document.getElementById('gapage').value;
						
				 		//_gaq.push(['_setAccount','<?= (strlen($googleAnalyticsCode) > 0) ? $googleAnalyticsCode : 'UA-9264241-3'; ?>']);
				 		_gaq.push(['_trackPageview',gapagevalue]);
		
						if(hasMoonTracker) {
							//_gaq.push(['b._setAccount','<?= $googleAnalyticsCodeMoon ?>']);
							_gaq.push(['b._trackPageview',gapagevalue]);					
						}
					}
					
					activityIndicator(0);
					window.scrollTo(0,0);
				}
			}catch(e){
				errorLog(['showDatasetDetails 1',e.message,false]);
			}
		}
		
		if (!supportAnimation){
			if (detailsShowing()){
				document.getElementById(dataset+'_'+featureId+'_details_div').style.display = "none";
			}else{
				document.getElementById(dataset+'_'+featureId+'_results_div').style.display = "none";
			}
			retrMessage(true);
		}
		eventAjaxObject.send(null);
	}catch(e){
		errorLog(['showDatasetDetails 2',e.message,false]);
	}
}

function showDatasetResults(dataset,featureId) {
		
	try{
		if(fromQBSearch == 1){
			document.getElementById('quickbeamsearch_row').style.display = "block";
			document.getElementById('qbResultsPane').style.display = "block";
			fromQBSearch = 0;
		}
		if(supportAnimation) {
			var rightPage = document.getElementById(dataset+'_'+featureId+'_results_div');					
			var leftPage = document.getElementById(dataset+'_'+featureId+'_details_div');
			pageAnimation(rightPage,leftPage,"slide",0);					
		} else {	
			document.getElementById(dataset+'_'+featureId+'_details_div').style.display = "none";
			document.getElementById(dataset+'_'+featureId+'_results_div').style.display = "block";
		}
	} catch(e) {
		errorLog(['showDatasetResults',e.message,false]);
	}
}

function showDatasetSearch(dataset,featureId) {
	try{
		document.getElementById(dataset+'_'+featureId+'_details_div').style.display = "none";
		if(supportAnimation) {
			var rightPage = document.getElementById(dataset+'_'+featureId+'_search_div');					
			var leftPage = document.getElementById(dataset+'_'+featureId+'_results_div');
			pageAnimation(rightPage,leftPage,"slide",0);					
		} else {
			document.getElementById(dataset+'_'+featureId+'_details_div').style.display = "none";
			document.getElementById(dataset+'_'+featureId+'_results_div').style.display = "none";
			document.getElementById(dataset+'_'+featureId+'_search_div').style.display = "block";
		}
	} catch(e) {
		errorLog(['showDatasetSearch',e.message,false]);
	}
}

function datasetGeoToText(dataset,featureId) {
	try{
		document.getElementById(dataset+'_'+featureId+'_near_geo').style.display = "none";
		document.getElementById(dataset+'_'+featureId+'_near_text').style.display = "inline";
		document.getElementById(dataset+'_'+featureId+'_location').disabled = false;
	} catch(e) {
		errorLog(['datasetGeoToText',e.message,false]);
	}
}


var watchId;
var oldLat, oldLon;
var webKitGeoLocationUpdateInterval = 1000*60*5; //5 minutes

function setLocationWebKit(position){
	lat = position.coords.latitude;
	lon = position.coords.longitude;
}

function getCurrentGeo(){
	navigator.geolocation.getCurrentPosition(setLocationWebKit);
	doneGetLocation(geoLocationDataSet,geoLocationFeatureId);
}

function watchGeo(){
	try{
		if ((oldLat != lat && oldLon != lon) || (lat == 0 && lon == 0)){
			if (watchId == undefined){
				watchId = navigator.geolocation.watchPosition(setLocationWebKit);
			}else{
				navigator.geolocation.getCurrentPosition(setLocationWebKit);
			}
			oldLat = lat;
			oldLon = lon;
			setTimeout("watchGeo()",5000);
		}else{
			navigator.geolocation.clearWatch(watchId);
			watchId = null;
			setTimeout("watchGeo()",webKitGeoLocationUpdateInterval);
		}
	}catch(e){
		errorLog(['watchGeo',e.message,false]);
	}
}
	
var textToGeoBool = false;
function datasetTextToGeo(dataset,featureId) {
	textToGeoBool = true;
	getLocation(dataset,featureId);
}

var geoLocationDataSet;
var geoLocationFeatureId;
function getLocation(dataset,featureId){ 
	try {
		
		if(agent == 'Custombandapp'){
			document.getElementById(dataset+'_'+featureId+'_location').disabled = true;
			document.getElementById(dataset+'_'+featureId+'_search_submit').disabled = true;
			window.location.href = '#getLocation';
			activityIndicator(1);
			setTimeout('doneGetLocation("'+dataset+'",'+featureId+')',3000);
		}else{
			if(navigator.geolocation){
				document.getElementById(dataset+'_'+featureId+'_location').disabled = true;
				document.getElementById(dataset+'_'+featureId+'_search_submit').disabled = true;
				geoLocationDataSet = dataset;
				geoLocationFeatureId = featureId;
				activityIndicator(1);
				getCurrentGeo();
			}
		}
	}catch (e) {
		errorLog(['getLocation',e.message,false]);
	}
}

function doneGetLocation(dataset,featureId) {
	try{
		document.getElementById(dataset+'_'+featureId+'_search_submit').disabled = false;
		if (textToGeoBool){
			if (lat != 0 && lon != 0){
				document.getElementById(dataset+'_'+featureId+'_near_geo').style.display = "inline";
				document.getElementById(dataset+'_'+featureId+'_near_text').style.display = "none";
			}else{
				document.getElementById(dataset+'_'+featureId+'_location').disabled = false;
			}
			textToGeoBool = false;
		}
		activityIndicator(0);
	} catch(e) {
		errorLog(['doneGetLocation',e.message,false]);
	}
}

function addEvent(obj, evType, fn){ 
	try{
		if (obj.addEventListener){ 
			obj.addEventListener(evType, fn, false); 
			return true; 
		} else if (obj.attachEvent){ 
			var r = obj.attachEvent("on"+evType, fn); 
			return r; 
		} else { 
			return false; 
		}
	} catch(e) {
		errorLog(['addEvent',e.message,false]);
	}
}

function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}



function dynamicCountryChange(elem,id) {
	try{
		var elemId = elem.id;	
		var elemParts = elemId.split("_");		
		var stateDiv = document.getElementById(elemParts[0]+"_"+elemParts[1]+"_dynamic_"+elemParts[3]+"_state_div");
		var stateElem = document.getElementById(elemParts[0]+"_"+elemParts[1]+"_dynamic_"+elemParts[3]+"_state");
		var cityElem = document.getElementById(elemParts[0]+"_"+elemParts[1]+"_dynamic_"+elemParts[3]+"_city");
		
		if(elem.value == 0) {
			stateDiv.style.display = "none";
			return false;
		}
		
		activityIndicator(1);
		
		var eventAjaxObject;
		if(!(eventAjaxObject = new ajaxObj())){
			errorLog(['dynamicCountryChange','ajaxObject failed',false]);
		}
		
		var rightnow = new Date();
		eventAjaxObject.open('POST','/dataset/getstates/'+elemParts[1]+'/'+elem.value+'?ts='+rightnow.getTime(),true);	
		eventAjaxObject.onreadystatechange = function(){
			if (eventAjaxObject && eventAjaxObject.readyState == 4 && eventAjaxObject.status == 200){
				try {
					 var responseJSON = JSON.parse(eventAjaxObject.responseText);
					 
					 if(responseJSON.states.length < 2) { //>
						 stateDiv.style.display = "none";
						 stateElem.length = 1;
						 cityElem.disabled = false;
						 cityElem.focus();
					 } else {
						 stateElem.length = 1;
						 
						 for(var o in responseJSON.states) {						 
							 stateElem.options[stateElem.length] = new Option(responseJSON.states[o]['text'],responseJSON.states[o]['value']);
						 }
						 
						 stateDiv.style.display = "block"; 
					 }
				}catch(e){
					errorLog(['dynamicCountryChange',e.message,false]);
				}
				
				activityIndicator(0);
			} else if(eventAjaxObject.readyState == 4) {
				activityIndicator(0);
			}
		}
		
		eventAjaxObject.send();	
	} catch(e) {
		errorLog(['dynamicCountryChange',e.message,false]);
	}
}

function dynamicStateChange(elem,id) {
	var elemId = elem.id;	
	var elemParts = elemId.split("_");		
	var stateDiv = document.getElementById(elemParts[0]+"_"+elemParts[1]+"_dynamic_"+elemParts[3]+"_state_div");
	var stateElem = document.getElementById(elemParts[0]+"_"+elemParts[1]+"_dynamic_"+elemParts[3]+"_state");
	var cityElem = document.getElementById(elemParts[0]+"_"+elemParts[1]+"_dynamic_"+elemParts[3]+"_city");
	
	if(elem.value != "") { 
		cityElem.disabled = false;
		cityElem.focus();
	}
}

function onWindowResize() {
	//var rightnow = new Date();
	//document.title = rightnow.getTime();
	if(document.getElementById("maincon") != null) {
		try {
			document.getElementById("maincon").style.width = window.innerWidth+'px';
			if(backgroundType != "none") {
				document.getElementById("body").style.backgroundImage = "url('"+contentServer+"/image.php?b="+bandId+"&f="+bandId+"_background."+backgroundType+"&w="+window.innerWidth+"')";
			}
			document.getElementById("body").style.width = window.innerWidth+'px';
			//document.getElementById('backBar').innerHTML += "<span style='background-color: white'>"+window.innerWidth+'px</span>';
		}catch(e){
			errorLog(['onWindowResize',e.message,false]);
		}		
	}
}

function expander(element_id, arrow_id, large){
	//for expanding block elements
	try{
		var target_element = document.getElementById(element_id);
		var arrow_element = document.getElementById(arrow_id);
		if (target_element.style.display == "none" || target_element.style.display != "block"){
			target_element.style.display = "block";
			arrow_element.src= contentServer+"/images/expanderDown"+(large ? "Large" : "")+".gif"
		}else if (target_element.style.display == "block" || target_element.style.display != "none"){
			target_element.style.display = "none";
			arrow_element.src= contentServer+"/images/expanderRight"+(large ? "Large" : "")+".gif"
		}
	}catch(e){
		errorLog(['expander',e.message,false]);
	}			
}

function toRad(n){
	return n * Math.PI / 180;
}

function returnDistanceBetweenTwoPair(lat1,lon1,lat2,lon2){
	try{
		var R = 20903520; // Earth's radius in feet
		//var R = 6371; // km
		//var R = 3959; // miles
		var dLat = toRad((lat2-lat1));
		var dLon = toRad((lon2-lon1));
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
		Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.asin(Math.sqrt(a));
		var d = R * c;
		return d;
	}catch(e){
		errorLog(['returnDistanceBetweenTwoPair',e.message,false]);
	}		
}

function openSettings(settingElementId){
	try{
		if (document.getElementById(settingElementId)){
			if (document.getElementById(settingElementId).style.display == 'none'){
				document.getElementById(settingElementId).style.display = 'block';
			}else{
				document.getElementById(settingElementId).style.display = 'none';
			}
		}
	}catch(e){
		errorLog(['openSettings',e.message,false]);
	}		
}

function createSettings(settingElementId,parentId){
	try{
		if (document.getElementById(settingElementId) && document.getElementById(settingElementId+'_hidden')){
			document.getElementById(settingElementId+'_hidden').innerHTML = '';
			return;
		}
		var optionDiv = document.createElement('div');
		optionDiv.setAttribute('id',settingElementId);
		optionDiv.setAttribute('style','display: none');	
		optionDiv.appendChild(returnContentFor(settingElementId));
		document.getElementById(parentId).appendChild(optionDiv);
	}catch(e){
		errorLog(['createSettings',e.message,false]);
	}	
	
}

function returnContentFor(settingElementId){
	try{
		var elemParts = settingElementId.split('_');
		if (elemParts[2] == 'walkinglist' && elemParts[3] == 'options'){
			var optionDiv = document.createElement('div');
			optionDiv.setAttribute('class','walkinglist_options');
			optionDiv.innerHTML = document.getElementById(settingElementId+'_hidden').innerHTML;
			document.getElementById(settingElementId+'_hidden').innerHTML = '';
			return optionDiv;
		}
	}catch(e){
		errorLog(['returnContentFor',e.message,false]);
	}	
}

function doCheckBox(id){
	try{
		document.getElementById(id).checked = !document.getElementById(id).checked;
	}catch(e){
		errorLog(['doCheckBox',e.message,false]);
	}	
}

function submitLogin(){
	try{
		document.getElementById('gg_login_form').submit();
	}catch(e){
		errorLog(['submitLogin',e.message,false]);
	}	
}

function orientationChange(){
	hasBeenRotated = true;
	switch(window.orientation){
		case 0:
			//normal
			break;
		case -90:
			//right
			break;
		case 90:
			//left
			break;
		case 180:
			//flipped";
			break;
		}
}

var currentScale = 1;
var hasBeenRotated = false;
function setRescale(source,e){
	var comStr = "rescale('"+source+"','"+e.scale+"')";
	setTimeout(comStr,500);
}

function rescale(source,scale){
	if (hasBeenRotated){
		onWindowResize();
		hasBeenRotated = false;
	}
	currentScale = scale;
}

addEvent(window, 'load', onWindowResize);
window.onresize = onWindowResize; // Call onResizeWindow when windows is resized





