/**
 eLocal javascript functions
 */

var initAuto = false;

function loadNeeds( checkbox )
{
	if ( checkbox == undefined )
	{
		checked = $$("div.needs_box_common input:checked");
		checkbox = checked[0].id;
	}

	if( checkbox != undefined )
	{
		selected = $$("label[for="+checkbox+"]");
		$("select_title").update(selected[0].innerHTML);
	}
	else
	{
		$("select_title").update('Please select one');
	}
	return false;
}
needShow = false;
growing = false;
function showNeeds( checkbox )
{
	if($('categoriesFlyout_select_title') != undefined && $('categoriesFlyout_select_title').innerHTML == 'Please select one')
	{
		return false
	}
	else
	{
		if($('needs_box').style.display == 'none')
			needShow = false;
		else
			needShow = true;

		if( needShow == false && growing == false )
		{
			growing = true;
			Effect.Grow('needs_box', {direction: 'top-left', duration: 0.5, afterFinish: function() { growing = false } });
		}
		else if( growing == false )
		{
			growing = true
			Effect.Shrink('needs_box', {direction: 'top-left', duration: 0.5, afterFinish: function() { growing = false } });
		}

		if ( checkbox == undefined )
		{
			checked = $$("div.needs_box_common input:checked");
			checkbox = checked[0].id;
		}

		if( checkbox != undefined )
		{
			selected = $$("label[for="+checkbox+"]");
			$("select_title").update(selected[0].innerHTML);
		}
		else
		{
			$("select_title").update('Please select one');
		}
		return false;
	}
}

function showAddlNeeds()
{
	Effect.toggle('addl_needs_cont', 'blind', { duration: 0.3 });
	return false;
}

showCats = false;
growingCats = false;
function showFlyout( flyoutId, item, cpGroupId )
{
	if($(flyoutId).style.display == 'none')
		showCats = false;
	else
		showCats = true;

	if( showCats == false && growingCats == false )
	{
		growingCats = true;
		Effect.Grow(flyoutId, {direction: 'top-left', duration: 0.5, afterFinish: function() { growingCats = false } });
	}
	else if( growingCats == false )
	{
		growingCats = true
		Effect.Shrink(flyoutId, {direction: 'top-left', duration: 0.5, afterFinish: function() { growingCats = false } });
	}

	if( item != undefined )
	{

		item_id = $(flyoutId+'-'+item).getValue();
		selected = $$("label[for=flyout-"+item_id+"]");
		$(flyoutId+"_select_title").update(selected[0].innerHTML);
	}

	if( cpGroupId != undefined )
	{
		$$("input[type=checkbox]").each(function(cb) { cb.checked = 0 });
		$('select_title').innerText = "Please select one";


		if( $$('.'+cpGroupId) != '')
		{
			$('select_title').removeClassName('disabled');
			$$('.need_item').each(Element.hide);
			reshuffleCopypoints(cpGroupId);
			$$('.'+cpGroupId).each(Element.toggle);
		}
		else if ( $(cpGroupId) != null && $(cpGroupId).descendantOf('selectedCpGroups') == true)
		{
			toggleCpGroup(cpGroupId);
		}
		else if ( $(cpGroupId) == null )
		{
			return false;
		}
		else
		{
			moveCpGroup(cpGroupId);
		}
	}
}

function hideFlyout( flyoutId )
{
	Effect.Shrink(flyoutId, {direction: 'top-left', duration: 0.5, afterFinish: function() { growingCats = false } });
}

function showAddlFlyout( addlFlyoutId )
{
	Effect.toggle(addlFlyoutId, 'blind', { duration: 0.3 });
	return false;
}

//This is a special function for showing the flyout on the submissions/add page. It doesn't shrink the flyout after an item is selected to allow for multiselect
function showSubmissionFlyout( flyoutId, item, cpGroupId )
{
	if($(flyoutId).style.display == 'none')
		showCats = false;
	else
		showCats = true;

	if( showCats == false && growingCats == false )
	{
		growingCats = true;
		Effect.Grow(flyoutId, {direction: 'top-left', duration: 0.5, afterFinish: function() { growingCats = false } });
	}


	if( cpGroupId != undefined )
	{
		if( $$('.'+cpGroupId) != '')
		{
			$$('.'+cpGroupId).each(Element.toggle);
		}
		else if ($(cpGroupId).descendantOf('selectedCpGroups') == true)
		{
			toggleCpGroup(cpGroupId);
		}
		else
		{
			moveCpGroup(cpGroupId);
		}
	}

	if( item != undefined )
	{
		item_id = $(item).getValue();
		selected = $$("label[for=flyout-"+item_id+"]");
		this_count = 0;
		selected_cats = '';
		$$(".flyout-item input").each(function(a){
			if( a.checked )
			{
				this_count = this_count+1;
				this_label = $$("label[for="+a.id+"]")[0].innerHTML;
				selected_cats = selected_cats+this_label+'<br/>';
			}
		});
		if( this_count == 1 )
		{
			$(flyoutId+"_select_title").update(this_label);
			$(flyoutId+"_selected_cats").update();
		}
		else if( this_count == 0 )
		{
			$(flyoutId+"_select_title").update('Choose Legal Category');
			$(flyoutId+"_selected_cats").update();
		}
		else
		{
			$(flyoutId+"_select_title").update('Multiple Needs Selected');
			$$('#'+flyoutId+'_selected_cats > span.select_box')[0].update(selected_cats);
		}
	}
}

function toggleCpGroup( cpGroupId )
{
	$(cpGroupId).toggle();
	//$(cpGroupId).parent(2).toggle();
}

selected_cp_group_count = 0;
function moveCpGroup( cpGroupId )
{
	$(cpGroupId).wrap('div', { 'class' : 'selected-cp-group' } );
	current_cp_group = $(cpGroupId).up(0).innerHTML;
	$(cpGroupId).remove();
	$('selectedCpGroups').insert({ 'top' : current_cp_group } );
	$(cpGroupId).removeClassName('double-box-group');
	$(cpGroupId).addClassName('single-box-bottom');
	selected_cp_group_count = selected_cp_group_count+1;

	return false;
}

function reshuffleCopypoints( cpGroupId )
{
	breakpoint = Math.ceil($$('.'+cpGroupId).length/2)
	left_start_count = $$('.needs_left > .'+cpGroupId).length;
	right_start_count = $$('.needs_right > .'+cpGroupId).length;
	if( left_start_count < right_start_count )
	{
		to_add_count = breakpoint-left_start_count;
		for(i=0;i<to_add_count;i++)
		{
			copied_cp = $$('.needs_right > .'+cpGroupId).first();
			$$('.needs_right > .'+cpGroupId).first().remove();
			$$('.needs_left').first().insert(copied_cp);
		}
	}
	else if( right_start_count < left_start_count )
	{
		to_add_count = breakpoint-right_start_count;
		for(i=0;i<to_add_count;i++)
		{
			copied_cp = $$('.needs_left > .'+cpGroupId).first();
			$$('.needs_left > .'+cpGroupId).first().remove();
			$$('.needs_right').first().insert(copied_cp);
		}
	}
}

function nextNumber( field )
{
	if( field.value.length == 3 )
	{
		$($(field)).next(0).focus();
	}
}

function showHide( id )
{
	document.getElementById( 'show' + id ).style.display = 'block';
	document.getElementById( 'hide' + id ).style.display = 'none';
}

function showHideMenu( name )
{
	var menuItems = ["browse","zipcode","list","file","multi"];
	for ( var i in menuItems )
	{
		if( name != menuItems[i] )
			document.getElementById( menuItems[i] ).style.display = 'none';
		else
			document.getElementById( menuItems[i] ).style.display = 'block';
	}
}

function checkStats( id )
{
	if( id == '' )
	{
		document.getElementById( 'CityStats' ).checked = false;
		document.getElementById( 'CityStatsDiv' ).style.display = 'none';
	}
	else
	{
		document.getElementById( 'CityStats' ).checked = true;
		document.getElementById( 'CityStatsDiv' ).style.display = 'block';
	}
}

function sendIt()
{
	var zipcode = $('zipfinder_zipcode').getValue();
	window.location = '/zip/' + zipcode + '/0';
}

function markAsHuman()
{
	var form = $('ContactAddForm');
	form['ContactImahuman'].setValue( "1" );
}

function initAutoComplete()
{
	field_value = $('zipcode').getValue();
	if ( $('zipcode').getValue() == 'ZIP Code or City' || $('zipcode').getValue() == 'Enter Business Name' )
	{
		$('zipcode').setValue('');
	}
	if ( initAuto == false )
	{
		curCity = $('zipcode').getValue();
		if( field_value != 'ZIP Code or City' )
		{
			changeSearchType('city');
			$('zipcode').setValue(curCity);
		}
		initAuto = true;
	}
}

function submitHomeSearch()
{
	$('home_search_form').submit();
}

function submitInnerSearch()
{
	$('inner_search_form').submit();
}

function initInternalSearch( defaultVal )
{
	var type = 'zip';
	$('searchType').setValue('zipCity');
	if ( $('zipcode').getValue() == defaultVal )
	{
		$('zipcode').setValue('');
		ac.disable = true;
		ac = new Ajax.Autocompleter("zipcode", "autocomplete_choices", "/cities/search_autocomplete/", {paramName: "query", afterUpdateElement: submitInnerSearch });
	}
}

function changeSearchType( type )
{
	if (type == 'business')
	{
		initAuto = true;
		var type = 'business';
		ac.disable = true;
		ac = new Ajax.Autocompleter("zipcode", "autocomplete_choices", "/profiles/search_autocomplete/", {paramName: "query", afterUpdateElement: submitHomeSearch });
		$('zipcode').setValue('Enter Business Name');
		$('searchType').setValue('business');
		$('search_link_2').replace('<a id="search_link_2" onclick="changeSearchType(\'city\');">City/State</a>');
		return false;
	}
	else
	{
		initAuto = true;
		var type = 'zip';
		ac.disable = true;
		ac = new Ajax.Autocompleter("zipcode", "autocomplete_choices", "/cities/search_autocomplete/", {paramName: "query", afterUpdateElement: submitHomeSearch });
		$('zipcode').setValue('ZIP Code or City');
		$('searchType').setValue('zipCity');
		$('search_link_2').replace('<a id="search_link_2" onclick="changeSearchType(\'business\');">Business Name</a>');
		return false;
	}
}

function characterCheck( string )
{
	if ( string == parseInt(string) )
	{
		$('zipcode').writeAttribute('maxlength', '5' )
	}
	else
	{
		$('zipcode').writeAttribute('maxlength', null )
	}
}

function emailcheck( str )
{
	if( str == undefined )
	{
		return true;
	}

	var at="@";
	var dot=".";
	var lat=str.indexOf( at );
	var lstr=str.length;
	var ldot=str.indexOf( dot );

	if( lat == -1 || lat == 0 || lat == lstr || ldot == -1 || ldot == 0 || ldot == lstr ||
		( str.indexOf( at, ( lat+1 ) ) != -1 ) || ( str.substring( lat-1, lat ) == dot ) ||
		( str.substring( lat+1, lat+2 ) == dot ) || ( str.indexOf( dot, ( lat+2 ) ) == -1 ) ||
		( str.indexOf( " " ) !=-1 ) )
	{
		return false;
	}

	return true;
}

function loadAjaxPage( hash )
{
	if ( hash == "About_Us" )
	{
	    var page = new Ajax.Updater('right-panel', '/loadAjaxPage/pages/about', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else if ( hash == "Advertising" )
	{
	    var page = new Ajax.Updater('right-panel', '/loadAjaxPage/pages/advertising', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else if ( hash == "Contact_Us" )
	{
	    var page = new Ajax.Updater('right-panel', '/loadAjaxPage/contacts/add/', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else if ( hash == "Update_Listing" )
	{
	    var page = new Ajax.Updater('right-panel', '/loadAjaxPage/advertisements/update/free/', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else if ( hash == "Terms" )
	{
	    var page = new Ajax.Updater('right-panel', '/loadAjaxPage/pages/terms', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else if ( hash == "Privacy" )
	{
	    var page = new Ajax.Updater('right-panel', '/loadAjaxPage/pages/privacy', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else if ( hash == "" )
	{
		var page = new Ajax.Updater('right-panel', '/loadAjaxPage/pages/about', { evalScripts: true, insertion: Element.replace });
		$('header').scrollTo();
		window.document.body.scrollTop = 0;
    	window.document.documentElement.scrollTop = 0;
	}
	else
	{
	    //var page = new Ajax.Updater('right-panel', '/#' + hash, { evalScripts: true, insertion: Element.replace });
	}
	//var page = new Ajax.Updater('right-panel', '/information/' + arg );
}

Event.observe(document, 'dom:loaded', function()
{
	hist = new Prototype.History(function(e)
	{
		var url = window.location;
		var hashstring = url.toString();
		if ( hashstring.search(/#/) != -1 )
		{
			var hash = hashstring.gsub(/^.*#/, '');
			loadAjaxPage( hash );
		}
	});
	$('header').scrollTo();
	window.document.body.scrollTop = 0;
    window.document.documentElement.scrollTop = 0;
});

function checkThis( form )
{
	var cSet = form.elements;
	for( var i = 0; i < cSet.length; i++ )
	{
		if( cSet[i].type=='checkbox' )
		{
			cSet[i].checked = cSet[i].checked ? false : true;
		}
	}
}

function validateForm( form )
{
    var errors = '';
    var form = $('ContactAddForm');

    if( form['ContactName'].getValue() == '' )
    {
    	errors += "Please enter your name.\n";
    }
    if( form['ContactPrimaryPhone1'].getValue().length == '' || form['ContactPrimaryPhone2'].getValue().length == '' || form['ContactPrimaryPhone3'].getValue().length == '' )
    {
    	errors += "Please enter your primary phone.\n";
    }
    else if( isNaN( form['ContactPrimaryPhone1'].getValue() ) || isNaN( form['ContactPrimaryPhone2'].getValue() ) || isNaN( form['ContactPrimaryPhone3'].getValue() ) ||
    	form['ContactPrimaryPhone1'].getValue().length < 3 || form['ContactPrimaryPhone2'].getValue().length < 3 || form['ContactPrimaryPhone3'].getValue().length < 4 )
    {
    	errors += "Please enter a valid primary phone.\n";
    }
    if( form['ContactEmail'].getValue() == '' )
    {
    	errors += "Please enter your email.\n";
    }
    else if( !emailcheck( form['ContactEmail'].getValue() ) )
    {
    	errors += "Please enter a valid email.\n";
    }
    if( form['ContactCity'].getValue() == '' )
    {
    	errors += "Please enter your city.\n";
    }
    if( form['ContactState'].getValue() == '' )
    {
    	errors += "Please select your state.\n";
    }
    if( form['ContactZip'].getValue() == '' )
    {
    	errors += "Please enter your zip.\n";
    }
    else if( isNaN( form['ContactZip'].getValue() ) || form['ContactZip'].getValue().length < 5 )
    {
    	errors += "Please enter a valid zip.\n";
    }
    if( form['ContactSubject'].getValue() == '' )
    {
    	errors += "Please select a subject.\n";
    }
    if( form['ContactMessage'].getValue() == '' )
    {
    	errors += "Please enter your message.\n";
    }
    if( errors != '' )
    {
    	alert( errors );
    	return false;
    }
    document.getElementById( 'ContactState' ).disabled=false;
    document.getElementById( 'ContactCity' ).disabled=false;
    return true;
}

function submitListingPhone( form )
{
	var errors = '';
	if( form['phone1'].getValue() == '' || isNaN( form['phone1'].getValue() ) )
		errors = "Please enter a valid phone number.";
	else if ( form['phone2'].getValue() == '' || isNaN( form['phone2'].getValue() ) )
		errors = "Please enter a valid phone number.";
	else if ( form['phone3'].getValue() == '' || isNaN( form['phone3'].getValue() ) )
		errors = "Please enter a valid phone number.";
    if( errors != '' )
    {
    	alert( errors );
    	return false;
    }
	return true;
}

var oldInp=0;
function shiftCheck(evt)
{
	evt=(evt)?evt:event;
	var target=(evt.target)?evt.target:evt.srcElement;
	if(!evt.shiftKey)
	{
		oldInp=target.id.substr(4);
		return false;
	}
	target.checked=1;
	var low=Math.min(target.id.substr(4),oldInp);
	var high=Math.max(target.id.substr(4),oldInp)
	var uncheck=1;
	for(var i=low;i<=high;i++)
	{
		uncheck &= document.getElementById('chk_'+i).checked;
		document.getElementById('chk_'+i).checked=1;
	}
	if(uncheck)
	{
		for(i=low;i<=high;i++)
		{
			document.getElementById('chk_'+i).checked=0;
		}
	}
	return true;
}

/*
 * Prototype history
 *
 * -----------------
 *
 * Based on jQuery history plugin
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari), modified by Lincoln Cooper
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

Object.extend(Prototype.Browser, {
  Safari: (function() {
    return navigator.appVersion.match(/Safari/) != null
  })(),

  version: (function() {
    if ( Prototype.Browser.WebKit ) {
      var version = 4;
      return parseFloat(version)
    }

    return 10
  })()
});

Prototype.History = Class.create({
  initialize: function(callback){
    this.historyCallback = callback;
    var current_hash = location.hash;

    this.historyCurrentHash = current_hash;
    if ((Prototype.Browser.IE) ) { // && (jQuery.browser.version < 8)
      // To stop the callback firing twice during initilization if no hash present
      if (this.historyCurrentHash == '') {
      this.historyCurrentHash = '#';
    }

      // add hidden iframe for IE
      $$("body").first().innerHTML += '<iframe id="proto_history" style="display: none;"></iframe>';
      var ihistory = $("proto_history");
      var iframe = ihistory.contentWindow.document;
      iframe.open();
      iframe.close();
      iframe.location.hash = current_hash;
    }
    else if (Prototype.Browser.WebKit && ( Prototype.Browser.version < 4 )) {
      // etablish back/forward stacks
      this.historyBackStack = [];
      this.historyBackStack.length = history.length;
      this.historyForwardStack = [];

      this.isFirst = true;
    }
    this.historyCallback(current_hash.replace(/^#/, ''));
    setInterval(this.historyCheck.bind(this), 100);
  },

  historyAddHistory: function(hash) {
    // This makes the looping function do something
    this.historyBackStack.push(hash);

    this.historyForwardStack.length = 0; // clear forwardStack (true click occured)
    this.isFirst = true;
  },

  historyCheck: function(){
    if ( Prototype.Browser.IE ) { // && (jQuery.browser.version < 8)
      // On IE, check for location.hash of iframe
      var ihistory = $("proto_history");
      var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
      var current_hash = iframe.location.hash;
      if(current_hash != this.historyCurrentHash) {

        location.hash = current_hash;
        this.historyCurrentHash = current_hash;
        this.historyCallback(current_hash.replace(/^#/, ''));

      }
    } else if (Prototype.Browser.Safari && ( Prototype.Browser.version < 4 )) {
      if (!this.dontCheck) {
        var historyDelta = history.length - this.historyBackStack.length;

        if (historyDelta) { // back or forward button has been pushed
          this.isFirst = false;
          if (historyDelta < 0) { // back button has been pushed
            // move items to forward stack
            for (var i = 0; i < Math.abs(historyDelta); i++) this.historyForwardStack.unshift(this.historyBackStack.pop());
          } else { // forward button has been pushed
            // move items to back stack
            for (var i = 0; i < historyDelta; i++) this.historyBackStack.push(this.historyForwardStack.shift());
          }
          var cachedHash = this.historyBackStack[this.historyBackStack.length - 1];
          if (cachedHash != undefined) {
            this.historyCurrentHash = location.hash;
            this.historyCallback(cachedHash);
          }
        } else if (this.historyBackStack[this.historyBackStack.length - 1] == undefined && !this.isFirst) {
          // back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
          // document.URL doesn't change in Safari
          if (document.location.hash.indexOf('#') >= 0) {
            this.historyCallback(document.location.hash.split('#')[1]);
          } else {
            var current_hash = location.hash;
            this.historyCallback('');
          }
          this.isFirst = true;
        }
      }
    } else {
      // otherwise, check for location.hash
      var current_hash = location.hash;
      if(current_hash != this.historyCurrentHash) {
        this.historyCurrentHash = current_hash;
        this.historyCallback(current_hash.replace(/^#/, ''));
      }
    }
  },
  historyLoad: function(hash){
    var newhash;

    if (Prototype.Browser.WebKit && ( Prototype.Browser.version < 4 )) {
      newhash = hash;
    }
    else {
      newhash = '#' + hash;
      location.hash = newhash;
    }
    this.historyCurrentHash = newhash;

    if ((Prototype.Browser.IE)) { // && (jQuery.browser.version < 8)
      var ihistory = $("jQuery_history");
      var iframe = ihistory.contentWindow.document;
      iframe.open();
      iframe.close();
      iframe.location.hash = newhash;
      this.historyCallback(hash);
    }
    else if (Prototype.Browser.WebKit && ( Prototype.Browser.version < 4 )) {
      this.dontCheck = true;
      // Manually keep track of the history values for Safari
      this.historyAddHistory(hash);

      // Wait a while before allowing checking so that Safari has time to update the "history" object
      // correctly (otherwise the check loop would detect a false change in hash).
      var fn = function() {this.dontCheck = false;};
      window.setTimeout(fn, 200);
      this.historyCallback(hash);
      // N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
      //      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
      //      URL in the browser and the "history" object are both updated correctly.
      location.hash = newhash;
    }
    else {
      this.historyCallback(hash);
    }
  }
});

function popUp(goUp)
{
	popUp(goUp,"","")
}

function popUp( goUp, category, zipcode )
{
	if( goUp )
	{
		new Ajax.Updater( 'popup', '/leads/newlead/0/ajax?category=' + category + '&zipcode=' + zipcode, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'popup']})

		$('overlay').setStyle({'height': $('content').getHeight() + 238 + 'px'});
		$('popup').setStyle({marginTop: document.viewport.getScrollOffsets().top + 'px'});

		$('overlay').setStyle({ display: 'block' });
		$('popup').setStyle({ display: 'block' });
	}
	else
	{
		$('overlay').setStyle({ display: 'none' });
		$('popup').setStyle({ display: 'none' });
	}
	return false;
}
function businessTime()
{
	Effect.toggle( 'business-search', 'slide', { duration: 0.5 } );
}
function showSub( subDropId )
{
	Effect.toggle( subDropId, 'appear', { duration: 0 } );
	Effect.toggle( subDropId+'-close', 'appear', { duration: 0 } );
}

