// Make our dropdowns work in IE
startList = function() {
	var menus = Array("links","myworld-menu");
	if (document.all&&document.getElementById) {
		for(k=0; k<menus.length; k++){
			navRoot = document.getElementById(menus[k]);
			if (navRoot != null) {
				for (i=0; i<navRoot.childNodes.length; i++) {
					node = navRoot.childNodes[i];
					if (node.nodeName=="LI") {
						node.onmouseover=function() {
							this.className+=" over";
						}
						node.onmouseout=function() {
							this.className=this.className.replace(" over", "");
						}
					}
				}
			}
		}	
	 }
}
window.onload=startList;


/************************************************************
* Global tasks...
************************************************************/

// Browser check
if(navigator.appVersion.indexOf("MSIE") != -1) is_ie = true
else is_ie = false

// Show message at mouse position
function showSavingMsg(msg){
	
}

/************************************************************
* Popups
************************************************************/

// Popup: report abuse
function zoom_cover(img){
	//alert("Zooming: "+img);
	popup(ZOOM_COVER_URL+"?imgurl="+encodeURIComponent(img),20,20,930,620);
}

var popUpWin=0;
function popup(url, left, top, width, height){
  if(popUpWin){
	if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = window.open(url, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

/************************************************************
* Starring
************************************************************/

var star_request = false;

// Calls starring function in Middleware
function savestar(itemId, status){
	
	if(status == "on") action = "star"
	else action = "unstar"
	
	//alert("Calling AJAX: "+itemId+" => "+action);
	
	star_request = ajax_init();
	if(star_request){
		star_request.onreadystatechange = starRegistered;
		star_request.open('GET', STAR_ITEM_URL + "?resource_id=" + itemId + "&action=" + action , true);
		star_request.send(null);
	}	
}

// Called when starring is done
function starRegistered() {
	if (star_request.readyState == 4) {
		if (star_request.status == 200) {
			//alert(star_request.responseText);
			return true;
		} else {
			alert('There was a problem with the request.');
		}
	}
} 
	
// Takes a star id (e.g. "photos-20300000000002") 
// and updates star status in global array
function updateStar(starID,status){

	var parts = starID.split("-")
	var itemid = parts[parts.length-1]

	var label = document.getElementById(starID + "-label")

	// Call AJAX
	savestar(itemid, status)
	//label.innerHTML = status=="on"?"Remove from My World":"Save to My World";	
	
}

// Starring
function star(starID,clicked){ // Called on mouseOver and mouseOut of a star

	var strOn  = "-on"		// on image
	var strOver  = "-over"    // over image
	var strOff = "-off"     // off image
	
	var oImg = document.getElementById(starID)
	
	var strImg = ""
	var status = ""
	
	// Get star name
	strImg = oImg.src
	
	// Is star already on?
	if (strImg.indexOf(strOn) > 0){
		if(clicked){
			oImg.src = strImg.replace(strOn,strOver)
			updateStar(starID,"off")
			Element.toggle(starID + '-label')
		}
		return
	}
	if (strImg.indexOf(strOver) > 0 && clicked){ // Turn ON the star
		status = "on"
		oImg.src = strImg.replace(strOver,strOn)
		updateStar(starID,status)
		return
	}else if (strImg.indexOf(strOver) > 0){ // Turn OFF the star
		oImg.src = strImg.replace(strOver,strOff)
		if (clicked) {
			updateStar(starID,status)
			return
		}
	}else {
		oImg.src = strImg.replace(strOff,strOver)
	}
}

function star_search(starID,searchString){ 

	var strOn  = "-on"		// on image
	var strOver  = "-over"    // over image
	var strOff = "-off"     // off image
	
	var oImg = document.getElementById(starID)
	
	var strImg = ""
	var status = ""
	
	// Get star name
	strImg = oImg.src
	
	// Is star already on?
	if (strImg.indexOf(strOn) > 0){
		oImg.src = strImg.replace(strOn,strOver)
		updateStar(starID,"off")
		return
	} else if (strImg.indexOf(strOver) > 0){ // Turn ON the star
		oImg.src = strImg.replace(strOver,strOn)
	
		var label = document.getElementById(starID + "-label")
		// Call AJAX to save the search
		search_request = ajax_init();
		if(search_request){
			//document.write(SAVE_SEARCH_URL + "?search_string=" + encodeURIComponent(searchString));
			//search_request.onreadystatechange = starRegistered;
			search_request.open('GET', SAVE_SEARCH_URL + "?search_string=" + encodeURIComponent(searchString), true);
			search_request.send(null);
		}	
	
		//label.innerHTML = "Remove from My World";	
	
		return
	}else {
		oImg.src = strImg.replace(strOff,strOver)
	}
}
/************************************************************
* Link Tracking
************************************************************/

function clicktrack(url) {
    if(document.images){
        (new Image()).src=url;
    }
    return true;
}

/************************************************************
* Feedback (Send via Ajax)
************************************************************/
function doFeedback(){
	
	// Start AJAX object
	feedback_request = ajax_init()
	
	// Get message
	var feedback = document.feedbackForm.feedback.value
	var page_url = document.feedbackForm.page_url.value
	var req_url = document.feedbackForm.req_url.value
	
	if(feedback_request){
		feedback_request.onreadystatechange = feedbackDone
		feedback_request.open('POST', FEEDBACK_URL , true)
        feedback_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		feedback_request.send("feedback=" + feedback + "&page_url=" + page_url + "&req_url=" + req_url)
		
		hidelyr('feedback-info')
		showlyr('feedback-sending')
	}
}
// Called when feedback is done sending
function feedbackDone() {
	if (feedback_request.readyState == 4) {
		if (feedback_request.status == 200) {
			hidelyr('feedback-sending')
			showlyr('feedback-thanks')
			return true
		} else {
			alert('There was a problem with the request.')
		}
	}
} 

/************************************************************
* Save a user Vital Stats
************************************************************/
function doSaveVitalStats(formname){
	
	// Get data
	var webuser_name = document[formname].webuser_name.value;
	var gender = document[formname].gender.value;
	var website = document[formname].website.value;
	var biography = document[formname].biography.value;
	var birthyear = document[formname].birthyear.value;
	var birthmonth = document[formname].birthmonth.value;
	var birthday = document[formname].birthday.value;
	
	// Build birthdate
	if(birthyear != "" && birthmonth != "" && birthday != ""){
		var birthdate = birthmonth + "-" + birthday + "-" + birthyear;
	}else var birthdate = "";
	
	// Build query string
	var q = "";
	if(webuser_name != "") q += "&webuser_name=" + encodeURIComponent(webuser_name);
	if(gender != "") q += "&gender=" + gender;
	if(birthdate != "") q += "&birthdate=" + birthdate;
	if(website != "") q += "&website=" + encodeURIComponent(website);
	if(biography != "") q += "&biography=" + encodeURIComponent(biography);
	
	// Start AJAX object
	ajax_req = ajax_init()
	
	//document.write (SAVE_PROFILE_URL + "?" + q);
	//return;
	
	if(ajax_req){
		ajax_req.onreadystatechange = doSaveVitalStatsDone;
		ajax_req.open('GET', SAVE_PROFILE_URL + "?" + q, true);
		ajax_req.send(null);
		
		hidelyr('vitalstats-edit')
		showlyr('vitalstats-saving')
	}
}
// Called when doSaveVitalState is done sending
function doSaveVitalStatsDone() {
	if (ajax_req.readyState == 4) {
		if (ajax_req.status == 200) {
			hidelyr('vitalstats-saving')
			showlyr('vitalstats-saving-done')
			return true
		} else {
			alert('There was a problem with the request.')
		}
	}
} 

/************************************************************
* Save a user Profile (bio)
************************************************************/
function doSaveProfile(formname){
	
	// Get data
	var biography = document[formname].biography.value;
	var website = document[formname].website.value;
	
	// Build query string
	var q = "";
	q += "&biography=" + encodeURIComponent(biography.substring(0,1023));
	if(website != "") q += "&website=" + encodeURIComponent(website);
	
	// Start AJAX object
	ajax_req = ajax_init()
	
	//document.write (SAVE_PROFILE_URL + "?" + q);
	//return;
	
	if(ajax_req){
		ajax_req.onreadystatechange = doSaveProfileDone;
		ajax_req.open('GET', SAVE_PROFILE_URL + "?" + q, true);
		ajax_req.send(null);
		
		hidelyr('profile-edit')
		showlyr('profile-saving')
	}
}
// Called when doSaveProfile is done sending
function doSaveProfileDone() {
	if (ajax_req.readyState == 4) {
		if (ajax_req.status == 200) {
			hidelyr('profile-saving')
			showlyr('profile-saving-done')
			return true
		} else {
			alert('There was a problem with the request.')
		}
	}
} 


/************************************************************
* Starred Items Public/Private (Send via Ajax)
************************************************************/
function doStarredItemsFlag(is_public){
	
	// Start AJAX object
	ajax_req = ajax_init()
	
	if(ajax_req){
		
		if(is_public){
			showlyr("starred_items_status_public");
			hidelyr("starred_items_status_private");
		}else{
			showlyr("starred_items_status_private");
			hidelyr("starred_items_status_public");
		} 
		
		ajax_req.onreadystatechange = starredItemsFlagDone
		ajax_req.open('GET', STARRED_ITEMS_FLAG_URL + "?is_public=" + is_public , true);
		ajax_req.send(null);
	}
	
}

// Called when doStarredItemsFlag is done sending
function starredItemsFlagDone() {
	if (ajax_req.readyState == 4) {
		if (ajax_req.status == 200) {
			return true
		} else {
			alert('There was a problem with the request.')
		}
	}
} 


/************************************************************
* AJAX
************************************************************/

// Initializes an AJAX object and returns it
function ajax_init(){
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) return false;
	else return http_request;
}

// Write to a div
function wd(dest,content){
	if (document.layers) {
	var newLayer;
	if(parentID){
		newLayer = eval('document.' + '.document.' + dest + '.document');
	}else{
	 newLayer = document.layers[dest].document;
	}
	newLayer.open();
	newLayer.write(content);
	newLayer.close();
	}else if (parseInt(navigator.appVersion)>=5&&navigator.appName=="Netscape") {
	document.getElementById(dest).innerHTML = content;
	}else if (document.all) {
	 document.all[dest].innerHTML = content ;
	}
}

// Show a layer
function showlyr(index) {
	var d = document.getElementById(index);
	d.className = "show-me";
}

// Hide a layer
function hidelyr(index) {
	var d = document.getElementById(index);
	d.className = "hide-me";
	
}


function show_splash(splash_id) {
	showlyr(splash_id);
}


function post_splash(splash_id, params) {
	hidelyr(splash_id + '-input');
	showlyr(splash_id + '-saving');

	var url;
	var onsuccess_function = function(serverResponse) {
		//$(splash_id + '-source').innerHTML = serverResponse.responseText;
		hidelyr(splash_id + '-saving');
		showlyr(splash_id + '-done');
	};
	var onerror_function = function() {
		hidelyr(splash_id + '-saving');
		showlyr(splash_id + '-error');
	};
	
	switch (splash_id) {
		case "splash-feedback":
			url = FEEDBACK_URL;
		break;
		case "splash-suggest-source":
			url = SUGGEST_SOURCE_URL;
		break;
		default: 
			alert(splash_id + " was not found");
	}

	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'post', 
				parameters: params, 
				onSuccess: onsuccess_function,
				onFailure: onerror_function,
				onException: onerror_function
			});
}

function post_splash_feedback() {
	var params = 'feedback=' + $('feedbackWindowText').value;
	params = params.replace('&','and');
	params += "\n\nBrowser: " + navigator.userAgent;
	params += '&page_url=' + window.location.href.replace(/#$/,'');
	return post_splash("splash-feedback", params);
}

function post_splash_suggest_source() {
	var params = 'req_url=' + $('suggested_source_url').value;
	return post_splash("splash-suggest-source", params);
}

function checkEnter(f, e){ //f is the passed form, e is event object passed from function invocation
	var characterCode //literal character code will be stored in this variable
	var executionString

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		executionString = 'document.' + f + '.submit()';
		eval(executionString) //submit the form
		return false
	}
	else{
		return true
	}

}


