function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}
function safeURLforAjax(str) {
	str=str.replace(/\&/g,'[[and]]');
	str=str.replace(/\?/g,'[[question]]');
	str=str.replace(/\%/g,'[[percent]]');
	return str;
}

function getCookie(Name){
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
}

function setCookie(name, value){
	document.cookie = name+"="+value
}

function changeModuleTab (id, selectedTab, selectedTabName) {
	var tabID = id + "Tab";
	var contentID = id + "Content";
	// hide active tab
	var i = 1;
	if ($(tabID+selectedTab).hasClassName('off')) {
		for (i=1;i<=$(tabID).childElements().length;i++){
            if ($(contentID+i)!=null) {
                $(tabID+i).removeClassName('on');
                $(tabID+i).addClassName('off');
                $(contentID+i).setStyle({ 'display':'none' });
            }
		}
		$(tabID+selectedTab).removeClassName('off');
		$(tabID+selectedTab).addClassName('on');
		$(contentID+selectedTab).setStyle({ 'display':'block' });
        
	}
    setCookie("citytabs", selectedTabName);
}

function getAnchorValue() {
    var anchorValue = location.hash;
    anchorValue = anchorValue.substring(1,(anchorValue.indexOf("/")>1?anchorValue.indexOf("/"):anchorValue.length));
    return anchorValue;
}

function toggleViewState (containerIDToToggle, labelIDToChange, visibleLabelText, hiddenLabelText, effect, speed) {
    if (!$(containerIDToToggle).visible()) {
        switch (effect) {
            case 'blind':
                Effect.BlindDown(containerIDToToggle, { duration: speed });
            break;
            case 'fade':
                Effect.Appear(containerIDToToggle, { duration: speed });
            break;
            default:
                $(containerIDToToggle).show();
        }
        $(labelIDToChange).update(visibleLabelText);
    } else {
        switch (effect) {
            case 'blind':
                Effect.BlindUp(containerIDToToggle, { duration: speed });
            break;
            case 'fade':
                Effect.Fade(containerIDToToggle, { duration: speed });
            break;
            default:
                $(containerIDToToggle).hide();
        }
        $(labelIDToChange).update(hiddenLabelText);
    }
}

var pageLoaded = false;

/********** IE HIGHLIGHT FORM INPUT FIX ************/
function IEHighlightFix() {
	var inputs = document.getElementsByTagName("input");
	if((navigator.appName=="Microsoft Internet Explorer") && document.all && document.getElementById) {
		for(j=0; j<document.forms.length;j++) {
			form = document.forms[j];
			for(i=0; i<form.length;i++) {
				if(form && form.elements[i] && form.elements[i].name) {
					navRoot = document.getElementById(form.elements[i].name);
					if(navRoot.nodeName == "INPUT") {	
						navRoot.onfocus=function() {
							if (this.className != "inputNoStyle" || this.className != "inputCheckbox") {
								this.className += "highlight";
								
							}
						}
						navRoot.onblur=function() {
							if (this.className != "inputNoStyle" || this.className != "inputCheckbox") {
								this.className = this.className.replace("highlight", "");
							}
						}
					}
				}
			}
		}
	}
}
function initializeIEFix() {
	if (document.getElementById('login_email')) {
		document.getElementById('login_email').focus();
		document.getElementById('login_email').background = "#FFFADB url(/inspace/images/input_active.gif) repeat-x";
	}
}
/********** IE HIGHLIGHT FORM INPUT FIX ************/

/********************* FORM HINTS ******************/
var previouslyHighlightedID = null;
function highlightDiv(newid) {
	if (previouslyHighlightedID == null && previouslyHighlightedID != newid){
		$(newid).addClassName('formBlockHighlighted');
	} else {
		$(previouslyHighlightedID).removeClassName('formBlockHighlighted');
			$(newid).addClassName('formBlockHighlighted');
	}
	previouslyHighlightedID = newid;
}

function showHint(id,highlightID) {
	if (document.getElementById(id + "_hint").style.display == "inline") {
		document.getElementById(id + "_hint").style.display = "none";
		document.getElementById(id).className = document.getElementById(id).className.replace("highlight", "");
		if (highlightID != null) {
			highlightDiv(highlightID);
		}
	} else {
		document.getElementById(id + "_hint").style.display = "inline";
		document.getElementById(id).className += "highlight";
		if (highlightID != null) {
			highlightDiv(highlightID);
		}
	}
}
/********************* FORM HINTS ******************/

function reportError(request) {
   $F('cartResult') = "An error occurred";
}
function reportCitySaveError(request) {
   $F('savedCity') = "An error occurred";
}

function manageCart(task,item) {
   if ($('buyCityId' + item)) {
   	  $('buyCityId' + item).innerHTML = '<img src="images/loader_16x16.gif" border="0" alt="Loading..." />';
   }
   var url = '/scripts/ajax/managecart.php';
   var url2 = '/scripts/ajax/checkcart.php';
   var params = task + '=' + item;
   var params2 = 'city=' + item;
   var ajax = new Ajax.Updater(
	          {success: 'cartResult'},
              url,
              {method: 'get', parameters: params, onFailure: reportError});
   var ajax2 = new Ajax.Updater(
             {success: 'buyCityId' + item},
               url2,
               {method: 'get', parameters: params2, onFailure: reportError})
}

function saveCity(task,cid) {
   var url = '/scripts/ajax/city_savecity.php';
   var params = task + '=' + cid;
   var ajax = new Ajax.Updater(
	         {success: 'saveBut'},
             url,
             {method: 'get', parameters: params, onFailure: reportCitySaveError});
}

function citylinks(task,id,cid,title,linkURL) {
	if (task == 'delete'){
		Effect.Shake('cityLinkItem'+id,{ distance: 3 });
		Effect.Fade('cityLinkItem'+id, { duration: 1.0 });
		var url = '/scripts/ajax/city_links.php';
		var params = 'action=' + task + '&linkID=' + id + '&cityID=' + cid;
		var successID = '';
	} else if (task == 'add'){
		var url = '/scripts/ajax/city_links.php';
		var params = 'action=' + task + '&cityID=' + cid + '&cityLinkTitle=' + title + '&cityLinkURL=' + linkURL;
		var successID = '';
	}
	var ajax = new Ajax.Request(url,
	 {
		 method: 'get',
		 success: successID,
		 onSuccess: function(request) {
			updateCityLinks(request.responseText,'success');
		 },
		 parameters: params,
		 onFailure: function(request) {
			updateCityLinks(request.responseText,'failure');
		 }
	 });
}

function updateCityLinks(responseText,request) {
	var resultArray = responseText.split('~~^.~~');
	Effect.Appear('linkAlertMsg', { duration: .3 });
	$('linkAlertMsg').update(resultArray[0]);
	if (resultArray[1] != null){
		if (resultArray[1].length > 0) {
			$('cityLinksList').insert(resultArray[1]);
		}
		if (resultArray[2] != "" && ($('noLinksMsg'))){
			$('noLinksMsg').remove();
		}
	}
	setTimeout("Effect.Fade('linkAlertMsg', { duration: .3 })",2000);
}

function updateCityAbout() {
   var form = $('aboutForm');
   var container = $('aboutContainer');
   container.innerHTML = '<img src="/images/loader_16x16.gif" border="0" alt="Loading..." />';
   form.request({
      method: 'get',
      onComplete: function(request){
         container.update(request.responseText);
         toggleViewState('aboutMeEdit', 'aboutMeEditTrigger', 'Close', 'Edit', 'fade', '.5');
      },
      onFailure: function(request) {
         container.insert({top: '<div class="alertMsgInline">Darn! An error.  I\'d refresh.</div>'});
      }
    })
}

function comment(task,userID,cid,commentID,comment) {
	if (task == 'delete'){
		Effect.Fade('comment-'+commentID, { duration: 1.0 });
		var url = '/scripts/ajax/city_comments.php';
		var params = 'action=' + task + '&commentID=' + commentID + '&cityID=' + cid + "&userID=" + userID;
		var successID = '';
	} else if (task == 'add'){
		var url = '/scripts/ajax/city_comments.php';
		var params = 'action=' + task + '&cityID=' + cid + "&userID=" + userID + "&commentMessage=" + comment;
		var successID = '';
	}
	var ajax = new Ajax.Request(url,
			 {
				 method: 'get',
				 success: successID,
				 onSuccess: function(request) {
					reportComment(request.responseText,'success');
				 },
				 parameters: params,
				 onFailure: function(request) {
					reportComment(request.responseText,'failure');
				 }
			 });
}

function reportComment(responseText,request) {
	var resultArray = responseText.split('~~^.~~');
	Effect.Appear('commentAlertMsg', { duration: .2 });
	$('commentAlertMsg').update(resultArray[0]);
	if (resultArray[1] != null){
		$('commentList').insert(resultArray[1]);
		Effect.Shake('comment-'+resultArray[2],{ distance: 3 });
		if (resultArray[2] != "" && ($('noCommentsMsg'))){
			$('noCommentsMsg').remove();
		}
	}
	setTimeout("Effect.Fade('commentAlertMsg', { duration: .3 })",2000);
}

function hotspot(task,id,cid,addParams) {
	if (task == 'delete'){
		Effect.Shake('divHotspotModuleList'+id,{ distance: 3 });
		Effect.Fade('divHotspotModuleList'+id, { duration: 1.0 });
		var url = '/scripts/ajax/city_hotspot.php';
		var params = 'action=' + task + '&hotspotID=' + id + '&cityID=' + cid;
		var successID = '';
	} else if (task == 'add'){
		var url = '/scripts/ajax/city_hotspot.php';
		var params = 'action=' + task + '&cityID=' + cid + '&' + addParams;
		var successID = '';
	}
	var ajax = new Ajax.Request(url,
			 {
				 method: 'get',
				 success: successID,
				 onSuccess: function(request) {
					reportHotspot(request.responseText,'success');
				 },
				 parameters: params,
				 onFailure: function(request) {
					reportHotspot(request.responseText,'failure');
				 }
			 });
}

function reportHotspot(responseText,request) {
	var resultArray = responseText.split('~~^.~~');

	if (resultArray[1] != null){
		$('hotspotModuleContent').insert({top: resultArray[1]});
		if ($('divHotspotModuleList'+resultArray[2])){ // check to make sure it exists
			Effect.Shake('divHotspotModuleList'+resultArray[2],{ distance: 3 });
            updateMarker(resultArray[3], resultArray[4]); // update the marker on the map [3] = lat, [4] = lng
		}
		if (resultArray[2] != "" && ($('noHotspotsMsg'))){
			$('noHotspotsMsg').remove();
		}
	}
    $('hotspotModuleContent').insert({top: '<div class="alertMsgInline" id="hotspotAlertMsg">'+resultArray[0]+'</div>'});
	setTimeout("Effect.Fade('hotspotAlertMsg', { duration: .3 })",2000);
}


function loadWikiText(targetID,city,state,country){
	var url = '/scripts/ajax/city_wikipedia.php';
	var params = 'targetID=' + targetID + '&city=' + city + '&state=' + state + '&country=' + country;
	var successID = targetID;
	var ajax = new Ajax.Request(url,
	 {
		 method: 'get',
		 success: successID,
		 onSuccess: function(request) {
			updateWikiModule(request.responseText,'success',targetID);
		 },
		 parameters: params,
		 onFailure: function(request) {
			updateWikiModule(request.responseText,'failure',targetID);
		 }
	 });
}

function updateWikiModule(responseText,request,id) {
	$('wikiLoadingIcon').remove();
	$(id).update(responseText);
}

function toggleDiv(id,linkID,linkText){
	if(linkID != ""){
		if ($(id).getStyle('display')=='none') {
			$(linkID).update(linkText);
		} else {
			$(linkID).update(linkText);
		}
	}
	Effect.toggle(id,'blind',{ duration: .5 });
}

function updateFlickr() {
   var form = $('flickrForm');
   var container = $('picModuleContent2');
   container.innerHTML = '<img src="/images/loader_16x16.gif" border="0" alt="Loading..." />';
   form.request({
      method: 'get',
      onComplete: function(request){
         container.update(request.responseText);
         fb.close();
      },
      onFailure: function(request) {
         container.insert({top: '<div class="alertMsgInline">Darn! An error.  I\'d refresh.</div>'});
      }
    })
}

function updateUserAbout() {
   var form = $('aboutForm');
   var container = $('aboutContainer');
   container.innerHTML = '<img src="/images/loader_16x16.gif" border="0" alt="Loading..." />';
   form.request({
      method: 'get',
      onComplete: function(request){
         container.update(request.responseText);
         toggleViewState('aboutMeEdit', 'aboutMeEditTrigger', 'Close', 'Edit', 'fade', '.5');
      },
      onFailure: function(request) {
         container.insert({top: '<div class="alertMsgInline">Darn! An error.  I\'d refresh.</div>'});
      }
    })
}

function updateUserCityBookmarks(cityId, target) {
   var targetContainer = target + "Container";
   var targetRow = target + "Row" + cityId;
   var url = '/scripts/ajax/user_del_city_bookmark.php?uid=<?=$userId?>&cityId='+cityId+'';
   var ajax = new Ajax.Request(url,{
      method: 'get',
      onSuccess: function(request){
         new Effect.Highlight(targetRow);
         $(targetRow).update(request.responseText);
         setTimeout("new Effect.DropOut('"+targetRow+"', { duration: .5 })",300);
      },
      onFailure: function(request) {
         $(targetContainer).insert({top: '<div class="alertMsgInline">Darn! An error.  I\'d refresh.</div>'});
      }
    })
}

function updateRSSLink() {
   var form = $('myBlogEditForm');
   var container = $('blogContainer');
   container.innerHTML = '<img src="/images/loader_16x16.gif" border="0" alt="Loading..." />';
   form.request({
      method: 'get',
      onSuccess: function(request){
         var resultArray = request.responseText.split('~~^.~~');
         container.update(resultArray[0]);
         if (resultArray[1] != null) {
            $('rssLinkIcon').setAttribute('href', resultArray[1]);
            $('rssLinkIconContainer').setStyle({'display': 'block'});
         } else {
             $('rssLinkIconContainer').setStyle({'display': 'none'});
         }
         fb.close();
      },
      onFailure: function(request) {
         container.update(request.responseText);
      }
    })
}