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

//create cookie for new visitor
/*
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=/";
}

//check if cookie is already there
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;
}

//erase cookie
function eraseCookie(name) {
	createCookie(name,"",-1);
}
*/

function slider_hide_shows(l_or_p){ 
	// l_or_p should equal 'larks' or 'places'
	$(l_or_p+"_list").style.display='none';
	//$('tag_list').style.display='none';
	//$('tag_clusters').style.display='none';
	//$('tag_clusters').innerHTML='';
	new Effect.Appear('loading');
	//new Effect.Appear('tags_loading');
	//new Effect.Appear('clusters_loading');
};

function select_p_l( l_id, txt, p_id ){
	//Update the hidden location/place fields in form
	// js does not have clean way of using default argument values, so just false for p_id when only location
	if (p_id) {
		$('lark_p_id').value=p_id;
		$('lark_l_id').value=l_id;
	}
	else {
		$('lark_l_id').value=l_id;
		$('lark_p_id').value=-1;
	}
	$('place_location_results').innerHTML = ''; //removes results but leaves div visible in case they search again
	// fancy pants on the selected_place div
	$('selected_place').innerHTML = txt;
	new Effect.Appear('selected_place', { duration: 2.0 });
	//Need to deactivate the observer, make txt change, then reactivate
	//$('place_query').value = txt;
};

function select_occ( occ_html ){
	// Insert the correct occurrence code into div for submit form
	$('disp_occ').innerHTML = occ_html;
};

function btn_swap(id, vote){
	// Replace vote buttons with images when clicked and return the opposite vote to its button form
	// 1:up 0:down
	if(vote==1){
		$('vote_up_'+id).innerHTML='<a href="#" class="up_active" onmouseover="Tip(\'Sounds Fun!\',PADDING,5,SHADOW, true,SHADOWWIDTH, 1,BGCOLOR, \'#fffaad\',BORDERCOLOR, \'#fc6\',FONTCOLOR, \'#333\',FONTWEIGHT, \'bold\',FONTSIZE, \'12px\')"></a>';
		$('vote_down_'+id).innerHTML='<a class="down" onclick="btn_swap('+id+', 0); new Ajax.Request(\'/larks/vote?lark_id='+id+'&vote=-1\', {asynchronous:true, evalScripts:true}); return false;" onmouseover="Tip(\'Not Interested\',PADDING,5,SHADOW, true,SHADOWWIDTH, 1,BGCOLOR, \'#fffaad\',BORDERCOLOR, \'#fc6\',FONTCOLOR, \'#333\',FONTWEIGHT, \'bold\',FONTSIZE, \'12px\')" href="#"></a>';
	}
	else if(vote==0){
		$('vote_down_'+id).innerHTML='<a href="#" class="down_active" onmouseover="Tip(\'Not Interested\',PADDING,5,SHADOW, true,SHADOWWIDTH, 1,BGCOLOR, \'#fffaad\',BORDERCOLOR, \'#fc6\',FONTCOLOR, \'#333\',FONTWEIGHT, \'bold\',FONTSIZE, \'12px\')"></a>';
		$('vote_up_'+id).innerHTML='<a class="up" onclick="btn_swap('+id+', 1); new Ajax.Request(\'/larks/vote?lark_id='+id+'&vote=1\', {asynchronous:true, evalScripts:true}); return false;" onmouseover="Tip(\'Sounds Fun!\',PADDING,5,SHADOW, true,SHADOWWIDTH, 1,BGCOLOR, \'#fffaad\',BORDERCOLOR, \'#fc6\',FONTCOLOR, \'#333\',FONTWEIGHT, \'bold\',FONTSIZE, \'12px\')" href="#"></a>';
	}
}

function qlc_handler(value, list){
	if(value=="cl"){
		location.href = "/locations/change_location"
	}
	else{
		new Ajax.Request('/locations/quick_change?l_id='+value+'&from='+list, {asynchronous:true, evalScripts:true}); 
		$('qc_id').style.display='none'; 
		new Effect.Appear('loading'); 
		return false;
	}
}

// The following function is used for counting characters within a form field
function getObject(obj) {
  var theObj;
  if(document.all) {
    if(typeof obj=="string") {
      return document.all(obj);
    } else {
      return obj.style;
    }
  }
  if(document.getElementById) {
    if(typeof obj=="string") {
      return document.getElementById(obj);
    } else {
      return obj.style;
    }
  }
  return null;
}

//Character Counter
function counter(enter,exit,text,characters) {
  var enterObj=getObject(enter);
  var exitObj=getObject(exit);
  var length=characters - enterObj.value.length;
  if(length <= 0) {
    length=0;
    text='<span class="disable"> '+text+' </span>';
    enterObj.value=enterObj.value.substr(0,characters);
  }
  exitObj.innerHTML = text.replace("{CHAR}",length);
}

// The following function is used to hijack the 'enter' key within a form 
// IF it is used the following way <input onkeypress="return js_on_enter(event, js_as_string)">
// This is Fing stupid, use prototype's observe and call the event instance's stop() method instead of using this crap
function js_on_enter(e, js)		// Takes event instance and js function
{
	if (!e) e = window.event; 
	if (e.keyCode == '13')
	{
		eval(js);
		return false;
	}
	return true;
}

function disable_element(sTargetId)
{
	document.getElementById(sTargetId).disabled = true;
}
function enable_element(sTargetId)
{
	document.getElementById(sTargetId).disabled = false;
}


// DEPRECATED !!!!!!!!!!!!!!!!!!!!  Use submit_on_enter_or_timeout
// The following function can be used to implement any js after a pause in user input; currently used to issue ajax requests
// srcElement is the text box id; js is the code to run after timeout; time is in ms; event object used to bypass timout with 'enter' key
function on_key_timeout(srcElement, js, time, oEvent)
{
	if (oEvent.keyCode == '13')
	{
		if (document.getElementById(srcElement).value.length > 1)
		{
			try { window.execScript(js); } catch (e) {}
			try { eval(js); } catch (e) {}
			if (window.global_timeout_id)
				clearTimeout(window.global_timeout_id);
		}
	}
	else
	{
		timeout_js_str = "if (document.getElementById(\"";
		timeout_js_str = timeout_js_str.concat(srcElement);
		timeout_js_str = timeout_js_str.concat("\").value.length > 1) ");
		timeout_js_str = timeout_js_str.concat(js);
		
		if (window.global_timeout_id)
		{
			clearTimeout(window.global_timeout_id);
			window.global_timeout_id = setTimeout(timeout_js_str,time);
		}
		else
		{
			window.global_timeout_id = setTimeout(timeout_js_str,time);
		}
	}
}

// DEPRECATED !!!!!!!!!!!!!!!!!!!!!!!!! 
// Use this function to kill current timeout, and execute js immediately
function kill_outstanding_timeout(js)
{
	if (window.global_timeout_id)
	{
		clearTimeout(window.global_timeout_id);
		try { window.execScript(js); } catch (e) {}
		try { eval(js); } catch (e) {}
	}
}



function testing()
{
	if (window.gobal_timeout_id)
		alert('true');
}


// on_key_timeout should be used in conjunction with a hidden button_to_function, which is where the javascript to be 
// evaluated should reside.  Therefore, on_key_timeout_or_enter accepts the following parameters: 
// button_id to submit; time_to_wait; and event (target_id and keypress will be determined from this)
var isIE = document.all ? 1 : 0;

// This is terrible, do not use this.
// should be using these for events in ie
// if (!e) e = window.event; 
// var target = (e.target) ? e.target : e.srcElement;
function submit_on_enter_or_timeout(button_id, time_to_wait, event)
{
	event_target = isIE ? event.srcElement : event.target;		// stupid IE hack
	
	if (event.keyCode == '13')
	{
		clearTimeout(window.global_timeout_id);
		document.getElementById(button_id).click();
		// ------------------TOTAL HACK------------------
		window.when_onfocus = event_target.value;			// This prevents re-submitting if the user tabs out after 'enter'
		window.place_onfocus = event_target.value;
		// ----------------------------------------------
	}
	else if (event.keyCode == '9')
	{
		// Let submit_on_val_change handle what to do
		clearTimeout(window.global_timeout_id);
	}
	else
	{
		// clear previous timeout and set a new one
		clearTimeout(window.global_timeout_id);
		// --------------- TOTAL HACK #2 -----------
		timeout_js = "if (window.enable_timeouts && document.getElementById('" + event_target.id + "').value.length > 0) document.getElementById('" + button_id + "').click(); " + "window.when_onfocus = document.getElementById('" + event_target.id + "').value;" + "window.place_onfocus = document.getElementById('" + event_target.id + "').value;";
		// -----------------------------------------
		window.global_timeout_id = setTimeout(timeout_js, time_to_wait);
	}
}



function submit_on_val_change(button_id, val1, val2)
{
	if ((val1 != val2) && (val2.length != 0))			// submit if strings are uniq and latest string has length > 0
	{
		document.getElementById(button_id).click();
	}
}

function update_tag_field()
{
	// Use this line to autofill the tag field:
	// Use this line to autosuggest:
	new Ajax.Request('/larks/call_auto_tagger', {asynchronous:true, evalScripts:true, parameters:'desc_text=' + escape($F('lark_description')) + ' ' + escape($F('lark_title')), onComplete:function(request){document.getElementById('autosuggest').innerHTML=request.responseText; document.getElementById('lark_suggested_tags').value=request.responseText;}});	
}

// Add another time function for one_time and daily larks
function addTime(type){       
        var times = document.getElementById(type+'times_table]');
        var clock = new Image();
        clock.src = '../images/clock.png';
        var error = new Image();
        error.src = '../images/warning.png';
        var ctr = document.getElementById(type+'count]').value * 1;
        ctr = ctr + 1;
        var startHR, startMIN, startAMPM;
        var endHR, endMIN, endAMPM;
        var errorBox, errorNum;

        if ( ctr > 10 ) {
                alert ("Enough Already! GoLark can't handle any more!");
        }else{
                //figure out occ type for error id's
                var findType = type.substring(0,6);
                var findMonthlyType = type.substring(0,10);
                if (findType == "occ_0["){
                        errorNum = type.replace(/[^\d]/g, '');
                        errorNum = errorNum.substring(1,errorNum.length);
                        errorNum = 'error_'+errorNum+'_timerow_';
                } else if (findType == "occ_1["){
                        errorNum = 'error_timerow_';
                } else if (findType == "occ_2["){
                        errorNum = type.substring(6,type.length);
                        errorNum = 'error_'+errorNum+'timerow_';
                } else if (findType == "occ_3_"){
                        //if occ_3 figure out if its dates or days
                        if (findMonthlyType == "occ_3_date"){
                            errorNum = type.replace(/[^\d]/g, '');
                            errorNum = errorNum.substring(1,errorNum.length);
                            errorNum = 'error_dates_'+errorNum+'_timerow_';
                        }
                        else {
                            errorNum = type.replace(/[^\d]/g, '');
                            errorNum = errorNum.substring(1,errorNum.length);
                            errorNum = 'error_days_'+errorNum+'_timerow_';
                        }
                }

                if (document.all){ //input.name doesn't work in IE
                        startHR = document.createElement('<input name="' +type+ 'startHR_' +ctr+ ']">');
                        startMIN = document.createElement('<input name="' +type+ 'startMIN_' +ctr+ ']">');
                        startAMPM = document.createElement('<select name="' +type+ 'startAMPM_' +ctr+ ']">');
                        endHR = document.createElement('<input name="' +type+ 'endHR_' +ctr+ ']">');
                        endMIN = document.createElement('<input name="' +type+ 'endMIN_' +ctr+ ']">');
                        endAMPM = document.createElement('<select name="' +type+ 'endAMPM_' +ctr+ ']">');
                        errorBox = document.createElement('<td name="'+errorNum+ctr+ '">');
                } else {
                        startHR = document.createElement('input');
                        startHR.name = type+"startHR_"+ctr+']';
                        startMIN = document.createElement('input');
                        startMIN.name = type+"startMIN_"+ctr+']';
                        startAMPM = document.createElement('select');
                        startAMPM.name = type+"startAMPM_"+ctr+']';
                        endHR = document.createElement('input');
                        endHR.name = type+"endHR_"+ctr+']';
                        endMIN = document.createElement('input');
                        endMIN.name = type+"endMIN_"+ctr+']';
                        endAMPM = document.createElement('select');
                        endAMPM.name = type+"endAMPM_"+ctr+']';
                        errorBox = document.createElement('td');
                        errorBox.name = errorNum+ctr;
                }

                startHR.id = startHR.name;
                startHR.type = "text";
                startHR.size = 2;
                startHR.maxLength = 2;
                startMIN.id = startMIN.name;
                startMIN.type = "text";
                startMIN.size = 2;
                startMIN.maxLength = 2;
                startAMPM.id = startAMPM.name;
                startAMPM.options[0] = new Option('AM');
                startAMPM.options[1] = new Option('PM');
				startAMPM.options[0].value = 'AM';
                startAMPM.options[1].value = 'PM';
                endHR.id = endHR.name;
                endHR.type = "text";
                endHR.size = 2;
                endHR.maxLength = 2;
                endMIN.id = endMIN.name;
                endMIN.type = "text";
                endMIN.size = 2;
                endMIN.maxLength = 2;
                endAMPM.id = endAMPM.name;
                endAMPM.options[0] = new Option('AM');
                endAMPM.options[1] = new Option('PM');
								endAMPM.options[0].value = 'AM';
                endAMPM.options[1].value = 'PM';
                errorBox.id = errorBox.name;
                errorBox.style.display = "none";
 
                var tbody = document.createElement('tbody');
                var row = document.createElement('tr');       
                var cell1 = document.createElement('td');
                var cell2 = document.createElement('td');
                var cell3 = document.createElement('td');
                var cell4 = document.createElement('td');
                var cell5 = document.createElement('td');

                cell1.appendChild(clock);
                cell2.appendChild(document.createTextNode('Start time: '));
                cell3.appendChild(startHR);
                cell3.appendChild(document.createTextNode(' : '));
                cell3.appendChild(startMIN);
                cell3.appendChild(document.createTextNode(' '));
                cell3.appendChild(startAMPM);
                cell4.appendChild(document.createTextNode('End time: '));
                cell5.appendChild(endHR);
                cell5.appendChild(document.createTextNode(' : '));
                cell5.appendChild(endMIN);
                cell5.appendChild(document.createTextNode(' '));
                cell5.appendChild(endAMPM);
                errorBox.appendChild(error);
                
                row.appendChild(cell1);
                row.appendChild(cell2);
                row.appendChild(cell3);
                row.appendChild(cell4);
                row.appendChild(cell5);
                row.appendChild(errorBox);
                tbody.appendChild(row);
                times.appendChild(tbody);

                document.getElementById(type+'count]').value = ctr;
                }
}

//Check the type of occurence
//Make the appropriate array
function checkType(type) {
        if (type == 'occ_0'){
            theArray = new Array("1","2","3","4","5","6","7","8","9","10");
        }
        else if (type == 'occ_2'){
            theArray = new Array("mon","tue","wed","thu","fri","sat","sun");
        }
        else if (type == 'occ_3_dates'){
            theArray = new Array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31");
        }
        else if (type == 'occ_3_days'){
            theArray = new Array("1","2","3","4","5","6","7","8","9","10");
        }
        return theArray;
}

//Remove item from array function
function removeItems(array, item) {
        var i = 0;
        while (i < array.length) {
                if (array[i] == item) {
                        array.splice(i, 1);
                } else {
                        i++;
                }
        }
        return array;
}

//Drop down function for how many dates on one-time and monthly dates form
function showDates(type, selected){
        for (i=selected; i > 0; i--){
                var activeTabs = document.getElementById(type+'['+i+'_tab]');
                var activeTimes = document.getElementById(type+'['+i+'_times]');
                activeTabs.className = "";
                activeTabs.style.display = "block";
                activeTimes.style.display = "none";
        }
        for (i=selected; i < 11; i++){
                var inActiveTabs = document.getElementById(type+'['+i+'_tab]');
                var inActiveTimes = document.getElementById(type+'['+i+'_times]');
                inActiveTabs.className = "";
                inActiveTabs.style.display = "none";
                inActiveTimes.style.display = "none";
        }
        //show tab selected
        var tab = document.getElementById(type+'['+selected+'_tab]');
        var times = document.getElementById(type+'['+selected+'_times]');
        tab.style.display = "block";
        tab.className = "active";
        times.style.display = "block";
}

//Toggle TABS for one-time, weekly, and monthly larks
function toggleTabs2(type, selected){
        var tab = document.getElementById(type+'['+selected+'_tab]');
        var times = document.getElementById(type+'['+selected+'_times]');
        var theArray = checkType(type);
        
        tab.style.display = "block";
        tab.className = "active";
        times.style.display = "block";

        //Make a new array all other tabs and times so you can hide them
        var theNewArray = removeItems(theArray, selected);
        for (i=0; i < theNewArray.length; i++) {
                var tabHide = document.getElementById(type+'['+theNewArray[i]+'_tab]');
                var timeHide = document.getElementById(type+'['+theNewArray[i]+'_times]');
                tabHide.className="";
                timeHide.style.display ='none';
        }  
}

//Toggle TABS for one-time, weekly, and monthly larks
function toggleTabs(type, selected){
        var checkbox = document.getElementById(type+'['+selected+'_checked]');
        var tab = document.getElementById(type+'['+selected+'_tab]');
        var times = document.getElementById(type+'['+selected+'_times]');
        var theArray = checkType(type);
        var fullArray = checkType(type);
 
        //Check the checkboxes
        //If changed to true
        if (checkbox.checked == true){
                tab.style.display = "block";
                tab.className = "active";
                times.style.display = "block";

                //Make a new array all other tabs and times so you can hide them
                var theNewArray = removeItems(theArray, selected);
                for (i=0; i < theNewArray.length; i++) {
                        var tabHide = document.getElementById(type+'['+theNewArray[i]+'_tab]');
                        var timeHide = document.getElementById(type+'['+theNewArray[i]+'_times]');
                        tabHide.className="";
                        timeHide.style.display ='none';
                } 
        }
        //If changed to false
        else if(checkbox.checked == false){
                tab.style.display = "none";
                tab.className = "";
                times.style.display = "none";
                
                //find another tab to reactivate here!
                var tabFound, reveal;
                for (i=0; i < theArray.length; i++){
                        var tabFind = document.getElementById(type+'['+theArray[i]+'_tab]');
                        if (tabFind.style.display == "block"){
                                reveal = theArray[i];
                                break;
                        }
                }
                //hide all the other tabs and times
                var theNewArray = removeItems(theArray, selected);  
                theNewArray = removeItems(theNewArray, reveal);   
                for (i=0; i < theNewArray.length; i++) {
                        var tabHide = document.getElementById(type+'['+theNewArray[i]+'_tab]');
                        var timeHide = document.getElementById(type+'['+theNewArray[i]+'_times]');
                        tabHide.className="";
                        timeHide.style.display ='none';
                }   
    
                //Check to see if there is nothing checked
                if (theArray.length < fullArray.length - 1){
                        var tabShow = document.getElementById(type+'['+reveal+'_tab]');
                        var timeShow = document.getElementById(type+'['+reveal+'_times]');
                        tabShow.className = "active";
                        timeShow.style.display = "block";
                }
                
        }          
}

//Toggle type of event on Submission Form
function toggleType(type){
        var show = document.getElementById(type);
        show.style.display = "block";
        theArray = new Array("one_time","daily","weekly","monthly");
        var theNewArray = removeItems(theArray, type);
        for (i=0; i < theNewArray.length; i++) {
                var hide = document.getElementById(theNewArray[i]);
                hide.style.display ='none';
        }
}

//Toggle between dates and days of monthly event
function toggleMonthly(type){
        var dates = document.getElementById("monthly_dates");
        var days = document.getElementById("monthly_days");
        if (type == "dates"){
                dates.style.display = "block";
                days.style.display = "none";
        }
        else if(type == "days"){
                days.style.display = "block";
                dates.style.display = "none";
        }
}

//Toggle Tags
function tagSelect(tag){
	tag.className == 'tagOFF' ? tag.className = 'tagON' : tag.className = 'tagOFF';
}

// Sort By Drop Down
var timeout	= 300;
var closetimer	= 0;
function toggleSort(id){
	var dd = document.getElementById(id);
	dd.style.visibility=="hidden" ? dd.style.visibility="visible" : dd.style.visibility="hidden"
}
function ddclose(){
	document.getElementById('dd').style.visibility="hidden";
}
function ddclosetime(){
	closetimer = window.setTimeout(ddclose, timeout);
}
function ddcancelclosetime(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

//Client Side Image Previewer
function previewImage(fileInfo) {
	var filename = "";
	//create the path to your local file
	if (fileInfo == null) {
		if (document.form1.file != "") {
		filename = "file:///" + document.form1.file.value;
	}
	} else {
		filename = fileInfo;
	}
	//check if there is a value
	if (filename == "") {
		alert ("Please select a image.");
		document.form1.file.focus();
	} else {
		//get the extension of the file to see if it has one of the image extensions
		var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
		if (fileExtension == "jpg" || fileExtension == "jpeg" || fileExtension == "gif" || fileExtension == "png"){	
			document.getElementById('preview').innerHTML = "<img src='file:/" + filename + "'>";
		} else {
			//if not extension fron list above write URL to file
			document.getElementById('preview').innerHTML = "nope";
		}
	}
}


function hide_fb_iframe() {
	 $('fb_logout_iframe').hide();
}


function addHandler(name,elem,func){
	if (window.addEventListener)
		elem.addEventListener(name,func,false);
	else
		elem.attachEvent('on'+name,func);
}

function whenSubmitter(){
	$('lark_when').onkeypress = function(e){
		if (!e) e = window.event;
		var target = (e.target) ? e.target : e.srcElement;

		if (e.keyCode == 13 && target.value != ''){
			$('lark_description').focus();			// func will be called on blur
			return false;
		}
		else{
			clearTimeout(window.larkWhenTimeout);
			window.larkWhenTimeout = setTimeout(nlpJaxRequest, 1500);
		}
	}
	$('lark_when').onblur = function(){
		clearTimeout(window.larkWhenTimeout);
		nlpJaxRequest();
	}
}


function nlpJaxRequest(){
	if ($('lark_when').value != '')
		new Ajax.Request('/larks/nlp_fill_form?query=' + escape($F('lark_when')) + "&today=" + $F('hidden_date_time'), {asynchronous:true, evalScripts:true});
}


//Show/Hide Toggle
function showhide(toggle){
	var txt = document.getElementById(toggle);
	if (toggle == 'toggleControls'){
		txt.innerHTML == "Show Options" ? txt.innerHTML = "Hide Options" : txt.innerHTML = "Show Options";
 	}
	else if (toggle == 'toggleTags'){
		txt.innerHTML == "SHOW TAGS" ? txt.innerHTML = "HIDE TAGS" : txt.innerHTML = "SHOW TAGS";
 	}
}

// Note this relies on Prototype's toPaddedString method
// Full year = %Y; month = %m; day = %d; hour = %H; minute = %M; second = %S
function fmtDate(fmt){
	var today = new Date();
	fmt = fmt.replace(/%Y/, today.getFullYear());
	fmt = fmt.replace(/%m/, (today.getMonth() + 1).toPaddedString(2));
	fmt = fmt.replace(/%d/, today.getDate().toPaddedString(2));
	fmt = fmt.replace(/%H/, today.getHours().toPaddedString(2));
	fmt = fmt.replace(/%M/, today.getMinutes().toPaddedString(2));
	fmt = fmt.replace(/%S/, today.getSeconds().toPaddedString(2));
	return fmt
}