// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var YAHOO = {};
var YMAPPID = "";
var MAPSCRIPTS_LOADED = false;
var LOADED_SCRIPTS = [];
var myMap = null;
var currentMap = null;
var currentMapMarkers = new Array();
var nearbyPlacesList = new Array();
var selectedPlace = null;

function filter(l){document.location = l;}
addGradient = function() {

	var divs = document.getElementsByTagName("div");
	
	for (var i=0; i<divs.length; i++) {
		if(divs[i].className.match('gradient')) {
			image = document.createElement('img');
			if(divs[i].className.match('dark')){
				image.setAttribute('src', '/images/gradient_dark.png');
			} else {
				image.setAttribute('src', '/images/gradient.png');
			}
			image.setAttribute('class', 'g');
			divs[i].appendChild(image);
		}
	}

}

function popitup(url) {
	newwindow = window.open(url,'name','height=500,width=885,scrollbars=1');
	if (window.focus) {newwindow.focus()}
	return false;
}

function stripString(string_to_trim){
    return string_to_trim.replace(/^\s+|\s+$/g,"");
}

function setPlace(placeId, placeName){
        $('place_id').value=placeId; 
//        $('place_name').value=placeName;
//        $('place_name_confirmation_icon').innerHTML='<span class="message">Place validated</span>';
        if( $('q_where') != null ){
            $('q_where').innerHTML='This experience was in <span>' + placeName + '</span>'; 
            $('q_where').className='answered';        
        }
        if( $('button_place_finish') != null ){
            $('button_place_finish').show();
        }        
    }

function hideElement(elementId){
    $(elementId).innerHTML='';
}

function placeValid(){
    if($('place_id').value==""){
        alert("Please confirm location first!");
        return false;
	}
	return true;
}

function loadScript(scriptpath){
	//window.alert( "Loaded:" + scriptpath);
	for( i=0; i<LOADED_SCRIPTS.length; i++ )
	   if( LOADED_SCRIPTS[i] == scriptpath )
	       return;

	LOADED_SCRIPTS.push( scriptpath )
	new Ajax.Request(scriptpath, {asynchronous:false, evalScripts: false, method:'get' }).evalResponse();
}

function putText(element,textToPut){
	$(element).innerHTML=textToPut;
}


// Function stub - redefined if map present
function loadMap(){}

// Search box related function
function sBoxRepairPosition(obj){
    $('searchbox_options_inner').style.bottom='';
    $('searchbox_options').style.height='';
    $('searchbox_options').style.bottom='';
}

// Search box related function       
var sBoxTimeout = 0;     
function sBoxUp(){
    sBoxTimeout = setTimeout("\
        Effect.Queues.get('searchxscope').each(function(e) { e.cancel() }); \
        new Effect.BlindUp('searchbox_options', {duration:0, queue: {position:'end', scope: 'searchxscope', limit: 1 }, afterFinish: sBoxRepairPosition }); \
        sBoxTimeout = 0; \
      ", 5000);
}
   
// Search box related function
function sBoxDown(){	   
    if( sBoxTimeout > 0 ){
        clearTimeout(sBoxTimeout);
        sBoxTimeout = 0;
    } else { 
        Effect.Queues.get('searchxscope').each(function(e) { e.cancel() });
        $('searchbox_options').style.bottom='0px';
        new Effect.BlindDown('searchbox_options', {duration:0, queue: {position:'end', scope: 'searchxscope', limit: 1}, afterFinish: sBoxRepairPosition });	       
    }
}


function showSelected(elem){
	var elems = elem.parentNode.getElementsByTagName("li");
	for (var i=0; i < elems.length; i++) {
		elems[i].className = "";
	};
	elem.className = "selected";
}

function setFriendFamilyPrivacy(){
    if($('privacy_family').checked==false && $('privacy_friends').checked==false){
        $('privacy_friends_family').checked=false;
        $('privacy_public').checked=true;
    }
    else $('privacy_friends_family').checked=true;
    return false;
}

function addPlaceManual( check_similar ){
	var placeName = $('manual_place_name').value;
	var lon = $('manual_place_longitude').value;
	var lat = $('manual_place_latitude').value;
	var population = $('manual_place_population').value;
	var country_id = $('country_id').value;
	if(lat=="" || lon==""){alert('You have not choosen place on the map!');return false;}
	if(country_id==""){alert('You have not choosen country!');return false;}
	if(placeName==""){alert('You have not choosen place name!');return false;}
	var placeParams = 'manual_place[name]='+placeName+'&manual_place[latitude]='+lat+'&manual_place[longitude]='+lon+'&manual_place[country_id]='+country_id+'&manual_place[population]='+population;
	if( check_similar )
	   placeParams += '&check_similar=1'
	new Ajax.Request('/experiences/create_place_manual/',{method:'post', postBody:placeParams, asynchronous:true, evalScripts:true, encoding:'UTF-8' }); 
}

  var placeValidationFired = false;
  function confirmLocation(){
      placeValidationFired = true;
      clearPlace();
      if(stripString($('place_name').value)==""){
          alert('Place name cannot be blank');
      }
      else{
	      $('places_messages').innerHTML= '<p><img src=\"/images/ajax_spinner.gif\" title=\"Searching...\" alt=\"Searching...\" />Searching, please wait...<\/p>';
	      $('places_validation_external').innerHTML= "";
	      $('places_validation').innerHTML= "";
	      $('places_validation').show();
	      var s = 'place_name=' + $('place_name').value ; // + '&country_id=' + $('country_id').value;
	      new Ajax.Request('/experiences/validate_place' , {method:'post', postBody:s, asynchronous:true, evalScripts:true}); 
		  return false;
      }
      return false; 
  }
  
  var oldLocationName = ""
  function hasLocationChanged( newLocationName ){
    if( oldLocationName != newLocationName ){
        oldLocationName = newLocationName;
        return true;
    }
    return false;
  }
  
function clearPlace(){
	$('place_id').value = "";
    $('place_name_confirmation_icon').innerHTML = "";
    return true;
}
		  

function cancelEditContent(content_id,content_type){
	if(content_id=="" || content_type==""){
		alert('Wrong params');
	}
	else{
	var html_id=content_type+'_'+content_id
	new Ajax.Request('/experiences2/cancel_edit_content/'+content_id,{method:'post',postBody:'type='+content_type,asynchronus:true,evalScripts:true,onLoading:function(request){showLoading(html_id,'Loading...')}})
	}
	return false;
}

function checkImageField(obj_name){
	if($('image_file').value==""){alert('You have not choosen an image!');return false;};
	return true;
}
function checkAudioField(obj_name){
	if($('audio_file').value==""){alert('You have not choosen the file!');return false;};
	return true;
}

function toolTip(html, obj_name){
	var html = html;
	if($(obj_name)){
		if(html){
			$(obj_name).innerHTML = html;
		}
		$(obj_name).show();
	}
}

function toggleAll( div_id, checkbox_id){
    var inputlist = $(div_id).getElementsByTagName("input");
    for (i = 0; i < inputlist.length; i++) {
	   if ( inputlist[i].getAttribute("type") == 'checkbox' ) {
			inputlist[i].checked = ( checkbox_id == undefined ? true : $(checkbox_id).checked);
	   }
	}
}

function showLoading(html_id, label_text){
	inner_html = '<p class="loader" style="width:100%; margin:0px 5px; padding: 5px 0px;"><img src="/images/ajax_spinner.gif" alt="loading" style="margin:0 5px;"/>';
	inner_html += '<span> ' + label_text + '... <\/span><\/p>';
	$(html_id).innerHTML = inner_html;
}

CalendarMonths = new Array
( "",
 "January",
 "February",
 "March",
 "April",
 "May",
 "June",
 "July",
 "August",
 "September",
 "October",
 "November",
 "December");

// remember tabs on homepage
function readCookies(){
	var cookies = new Array('locations','experiences','photos','members');
	for (var i=0; i < cookies.length; i++) {
		cookie = cookies[i];
		var x = readCookie(cookie);
		if (x) {
			cookieSwitch("top_"+cookie,x);
		}
	};

};

function tabSwitch(current_tab){
	//needs work so that a cookie is written out with right tabs
	var tabset = $(current_tab.parentNode.parentNode.id);
	var type = current_tab.parentNode.parentNode.id.replace("top_","");
	var current = current_tab.parentNode.id;
	var current_tab = $(current);		
	var tabs = tabset.childNodes;
	
	for (var i=0; i < tabs.length; i++) {
		if(tabs[i].nodeName == "LI"){
			tab = $(tabs[i].id);
			tab.className = "";
			var tab_content = tab.id.replace("_tab","_content");
			$(tab_content).style.display="none";
			
			if(current == tab.id){
				tab.className = "selected"
				var tab_content = tab.id.replace("_tab","_content");
				$(tab_content).style.display="block";
				createCookie(type,tabs[i].id,0);
			}
		}
	};
};

function cookieSwitch(tabset, tab){
	var tabs = $(tabset).childNodes;
	var toSelect = tab;
	
	for (var i=0; i < tabs.length; i++) {
		if(tabs[i].nodeName == "LI"){
			tab = $(tabs[i].id);
			tab.className = "";
			var tab_content = tab.id.replace("_tab","_content");
			$(tab_content).style.display="none";
			
			if(toSelect == tab.id){
				tab.className = "selected"
				var tab_content = tab.id.replace("_tab","_content");
				$(tab_content).style.display="block";
			}
		}
	};	
	
}

function hoverBlock(elem,onoff,color){
	var block = $(elem);
	switch(onoff)
	{
		case 'on':
			color = (color) ? color : "#ccffdc";
			block.style.backgroundColor = color;	
		break
		
		case 'off':
			block.style.backgroundColor = '';	
		break
	}
	
	};
	
function changeSlogan(elem){
	var slogan = $(elem);
	var sloganWord = slogan.getElementsByTagName("em")[0];
	var sloganClass = slogan.className;
	var slogans = new Array("inspire","help","guide");
	
	for (var i=0; i < slogans.length; i++) {
		if(slogans[i] == sloganClass){
			var nextone = i+1;
			if(nextone == slogans.length){
				nextone = 0;
			}
		}
	};
	slogan.className = slogans[nextone];
	if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer"){
		slogan.style.background = 'none';
		slogan.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/slogan_" + slogans[nextone] + ".png', sizing='crop')";
	} else {
		slogan.style.background = 'url("/images/slogan_'+slogans[nextone]+'.png")';
	}
	sloganWord.innerHTML = slogans[nextone];
};

function checkAttr(attr,value){
	new Ajax.Request('/profile/validate_member', {method:'post',postBody:'attr='+attr+'&value='+value, asynchronous:true, evalScripts:true});
	return false;
};

function ticked(checkbox,target,parent){
	var check = $(checkbox);
	if(check.checked == false){
		if(total_checked != 0){
			total_checked--;	
		}
	} else {
		total_checked++;			
	}
	if(total_checked==0){
		if(active != false){
			activation=0;
			active=false;
		} else {
			activation=2;
		}
	} else {
		if(active !=true){
			activation=1;	
			active=true;
		} else {
			activation=2;	
		}

	}
	buttonActivation(target,parent,activation);
};

function buttonActivation(target, parent, activation){
	if(activation==1){
		var buttons = $(parent);
		var to_change = $(target);
		var id = to_change.id;

		var source = to_change.src.replace("_inactive","");
		var width = "71";
		var height = "20";
		var button = document.createElement("input");
		
		button.setAttribute("type","image");
		button.setAttribute("src",source);
		button.setAttribute("id",id);
		button.setAttribute("width",width);
		button.setAttribute("height",height);
		buttons.replaceChild(button,to_change);	
				
	} else if(activation==0) {
		var buttons = $(parent);
		var to_change = $(target);
		var id = to_change.id;
		
		var source = to_change.src.replace(".png","_inactive.png");

		var image = document.createElement("img");
		image.setAttribute("src",source);
		image.setAttribute("id",id);
		buttons.replaceChild(image,to_change);			
	}
};

function resetChecks(){
	var checks = document.getElementsByTagName("input");
	for (var i=0; i < checks.length; i++) {
		if(checks[i].type=="checkbox"){
			checks[i].checked = false;	
		}
	};
};

// select all checkboxes
function selectAll(functions){
	var checks = document.getElementsByTagName("input");
	for (var i=0; i < checks.length; i++) {
		if(checks[i].type=="checkbox"){
			if(checks[i].checked==false){
				checks[i].checked=true;
				checks[i].onclick();
			}			
		}
	};
};

function optionsPanel(check, target){
	var target = $(target);
	if(check.checked){ 
		target.show(); 
	} else { 
		target.hide(); 
	}
};


function fixFormLabels(){
	var labels;

	// enable for IE and Safari
	if( document.all || navigator.userAgent.indexOf("Safari") > 0){
		labels = document.getElementsByTagName("label");

		$A(labels).each ( function(label){
			Event.observe(label, "click", function(){
				var target = $(this.getAttribute('for'));
				// Checkboxes or radio button labels
				if(target.type == 'checkbox' || target.type == 'radio') {
					target.checked = target.checked == false ? true : false;
					target.onclick();					
				} else { // Textareas and input fields, Select elements
					target.focus();
				}
			});
		});
	}
};

// cookies for rembering tabs
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
};

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
};

function eraseCookie(name) {
	createCookie(name,"",-1);
};

// execute the script when the page has loaded
Event.observe(window,"load", fixFormLabels);

//initiate lightbox
Event.observe(window, 'load', init, false);
Event.observe(window, 'resize', center, false);
//lightbox functions for centering on the fly and re-initiating them
function init(){Lightbox.init();};
function center(){($('box').style.display!="none"?Lightbox.center('box'):'')};