
//This is a list of facet flyouts 
var facet_flyouts=['facet_topic.bars_clubs.bar_type.wine_bar_flyout',
                   'facet_feature.features_flyout',
				   'facet_topic.restaurants.food_type.wine_flyout',
				   'facet_date.relative.nextmonth_flyout',
				   'facet_topic.arts_culture_lifestyle.museum.transportation_flyout',
                   'login']



var g_PopupIFrame=null;


function ToggleVideo(choice,src)
	{
	 link=$("video_switch_on");
	 video_window=$("video_window");
	 video_frame=$("demand_video");
	 if (choice)
	 {	  
	  link.style.display="none";
	  video_frame.src=src;	  
	  video_window.style.display="block";	
	 }
	 else
	 {video_window.style.display="none";
	  video_frame.src=src;  
	  link.style.display="block";
	  	
	 }
	 	
	}




function calculate_width(flyout_id)
{
 if (isIE()){
	 var divPopup;
	 divPopup=document.getElementById(flyout_id);
	 var count=0;
	 for (i=0;i < divPopup.childNodes.length ;i++)
	 {
	 	if(divPopup.childNodes[i].nodeName == "DIV")
		{count=count+1;}
	 }
	 width =(count)*150;
	 divPopup.style.width=(width+50)+"px";
 }
  	
}




function isIE()
  {var isie=false;
  	if(navigator.appName == "Microsoft Internet Explorer")
    {
       isie=true;
    }
	return isie;
  }


function close_flyout(flyout_id)
    {   var divPopup;
        divPopup=document.getElementById(flyout_id);
        divPopup.style.display = "none";
		if (isIE()  && g_PopupIFrame)
		{document.body.removeChild(g_PopupIFrame);
          g_PopupIFrame=null;}
    }






function cancel_register(referer) {
    if (confirm('Are you sure you would like to cancel your registration?') ){
        document.location.href = referer;
    }
}

function setVars(oVar, oData){
    if (oVar=='Yahoo') void(window.open(oData, 'MyWeb', 'toolbar=no,width=700,height=400'));
	else if (oVar=='Delicious') void(window.open(oData, 'delicious', 'toolbar=no,width=700,height=220'));
	else if (oVar=='Facebook') void(window.open(oData, 'sharer', 'toolbar=no,width=642,height=436'));
	else if (oVar=='Newsvine') void(window.open(oData, 'newsvine', 'width=650,height=445,resizable=no,scrollbars=no'));

   omnVar = oVar;
   //alert(omnVar);
   var s=s_gi(s_account);
     s.linkTrackVars='events,eVar27';
     s.linkTrackEvents='event11';
     s.events='event11';
     s.eVar27= omnVar;
     void(s.tl(this,'o','Social Bookmark Click'));
     s.events = '';
     s.eVar27 = '';
     s.linkTrackVars = 'None';
     s.linkTrackEvents = 'None';
}

function track_omniture_event(key,value){
    //alert(key + "='" + value + "';" );
    eval(key + "='" + value + "';" );
    void(s.tl())
    eval(key + "='';" );
}

function track_omniture_event_with_arr(keys,values){
    for (i=0;i<keys.size();i++) {
        key=keys[i];
        value=values[i];
        eval(key + "='" + value + "';" );
        //alert(key + "='" + value + "'" );
    }
    void(s.tl());
    
    for (i=0;i<keys.size();i++) {
        key=keys[i];
        eval(key + "='';" );
        //alert(key + "='" + value + "'" );
    }
}

function checkbox_select(form_name,name,value,checked) {
    var formblock= document.getElementById(form_name);
    var forminputs = formblock.getElementsByTagName('input');
    for (i = 0; i < forminputs.length; i++) {
        // regex here to check name attribute
        var regex = new RegExp(name, "i");
        if (regex.test(forminputs[i].getAttribute('name'))) {
            if (forminputs[i].value == value)  {
                forminputs[i].checked = checked;
            }
        }
    }
}

function search_submit() {
    $("sitesearch").submit();
}

function toggle_divs(div_ids) {
    for (var i = 0; i < arguments.length; i++) {
        var div_id = arguments[i]
        if ($(div_id)) $(div_id).toggle();
    }
}

var dialogOverlay;

var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, {
  initialize: function(id) {
    this.createOverlay();

    this.dialog_box = $(id);
    this.dialog_box.show = this.show.bind(this);
    this.dialog_box.hide = this.hide.bind(this);

    this.parent_element = this.dialog_box.parentNode;

    var e_dims = Element.getDimensions(this.dialog_box);
    var b_dims = Element.getDimensions(this.overlay);
    this.dialog_box.style.left = ((b_dims.width/2) - (e_dims.width/2)) + 'px';
    this.dialog_box.style.top = '12px';
  },

  createOverlay: function() {
    if($('dialog_overlay')) {
      this.overlay = $('dialog_overlay');
    } else {
      this.overlay = document.createElement('div');
      this.overlay.id = 'dialog_overlay';
      Object.extend(this.overlay.style, {
      	position: 'absolute',
      	top: 0,
      	left: 0,
      	zIndex: 200,
      	width: '100%',
      	height: '100%',
        backgroundColor: '#000',
      	display: 'none'
      });
      $('body').appendChild(this.overlay);
    }
  },

  moveDialogBox: function(where) {
    Element.remove(this.dialog_box);
    if(where == 'back')
      this.dialog_box = this.parent_element.appendChild(this.dialog_box);
    else
      this.dialog_box = this.overlay.parentNode.appendChild(this.dialog_box);
  },

  show: function() {
    this.overlay.style.height = $('body').getHeight()+300+'px';
    //this.overlay.onclick = this.hide.bind(this);
    this.selectBoxes('hide');
    new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
    this.moveDialogBox('out');
    this.dialog_box.style.display = ''
  },

  hide: function() {
    this.selectBoxes('show');
    if(this.overlay) new Effect.Fade(this.overlay, {duration: 0.1});
    this.dialog_box.style.display = 'none';
    this.moveDialogBox('back');
    $A(this.dialog_box.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
    if(this.overlay) Element.remove(this.overlay);
    this.overlay = null;
  },

  selectBoxes: function(what) {
    $A(document.getElementsByTagName('select')).each(function(select) {
      Element[what](select);
    });

    if(what == 'hide')
      $A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)})
  }
});

function open_dialog_overlay(div_id) {
    if(dialogOverlay) dialogOverlay.hide();
    if ( $(div_id) ) {
        dialogOverlay = new Dialog.Box(div_id);
        dialogOverlay.show();
    }
}

function close_dialog_overlay() {
    if(dialogOverlay) dialogOverlay.hide();
}

function show_change_password(id)
{
    new Ajax.Updater('change_password_form_div', '/change_password/' + id + '/edit', {asynchronous: false, evalScripts: true, method: 'GET'});
    open_dialog_overlay('change_password_wrapper');
}

function show_change_neighborhood(event, id)
{
    new Ajax.Updater('change_neighborhood_form_div', '/change_neighborhood/?id=' + id, {asynchronous: false, evalScripts: true, method: 'GET'});
    open_dialog_overlay('change_neighborhood_wrapper');
	// position_on_event controls the offsets on the light box
	position_on_event(event,'change_neighborhood_popup',-100,-200);
}

function close_change_neighborhood()
{
	close_dialog_overlay();
}


function submit_change_password()
{
    var cp_form = $('change_password_form');
    new Ajax.Updater('change_password_form_div', cp_form.action, {asynchronous: true, evalScripts: true, method: 'POST',
        postBody: 'current_password=' + cp_form.current_password.value + '&new_password=' + cp_form.new_password.value + '&new_password_confirmation=' + cp_form.new_password_confirmation.value + "&_method=put"});
    return false;
}

function close_change_password()
{
    close_dialog_overlay();
}

function confirm_change_password_success()
{
}

function show_enter_password(e, xoffset, yoffset)
{
  if (xoffset==null) xoffset = -420;
  if (yoffset==null) yoffset = 20;
  position_on_event(e,'login',xoffset,yoffset);
  Element.show('login');
  $('email').value ="";
  $('password').value ="";
  $('email').focus();
  
} 

function handleKeyPress(e){
	var key=e.keyCode || e.which;
	if (key==13){
		submit_enter_password();
		
	}
}
  
function show_enter_password_right(e)
{
  position_on_event(e,'login',-220,10);
  open_flyout('login');
} 
     
// function show_register(e)
// {
//   position_on_event(e,'register',-420,10);
//   Element.hide('login');
//   Element.show('register');
// }      

function position_on_event(event, id, xoffset, yoffset) {
  var posx=0,posy=0;
  if(event==null) event=window.event;
  if(event.pageX || event.pageY){//FFx
      posx=event.pageX;
      posy=event.pageY;
  }else if(event.clientX || event.clientY){//IE
      if(document.documentElement.scrollTop){
          posx=event.clientX-document.documentElement.scrollLeft;
          posy=event.clientY+document.documentElement.scrollTop;
      }else{
          posx=event.clientX-document.body.scrollLeft;
          posy=event.clientY-document.body.scrollTop;
      }
  }

  $(id).style.top = (posy+yoffset)+'px';
  $(id).style.bottom = null;
  $(id).style.left = (posx+xoffset)+'px';
  $(id).style.right = null;
//alert(posx+xoffset);
}



// function show_enter_password()
// {
//     new Ajax.Updater('enter_password_form_div', '/new', {asynchronous: false, evalScripts: true, method: 'GET'});
//     open_dialog_overlay('enter_password_wrapper')
// }
// 
function submit_enter_password()
{
    var cp_form = $('enter_password_form'); 
    new Ajax.Updater('enter_password_form_div', cp_form.action, {asynchronous: false, evalScripts: true, method: 'POST',
		postBody: 'email=' + cp_form.email.value + '&password=' + cp_form.password.value });
    return false;
}

function submit_register()
{
    $('user_form').submit(); 
}


function validate_email(email){
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    if ( filter.test(email) )
   {
      return true;
    }
    return false;
}

function clearField(e, default_text) {
    if (typeof default_text=="undefined" || (default_text==trim(e.value)) ) {
        e.value = "";
    }
    e.style.fontStyle = "normal";
    e.style.color = "#333333";
}

function trim( value ) {
        return LTrim(RTrim(value));
}

function RTrim( value ) {
        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");
}

function LTrim( value ) {
        var re = /\s*((\S+\s*)*)/;
        return value.replace(re, "$1");
}

function callVote() {
    var rating_type = document.vote_form.rating_type.value;
    var ratable_id = document.vote_form.ratable_id.value;
    var ratable_type = document.vote_form.ratable_type.value
    var rating_value ;
    var rating_value_radio_obj = document.vote_form.rating_value;
    for (var i = 0; i < rating_value_radio_obj.length; i++) {
        if (rating_value_radio_obj[i].checked) {
            rating_value = rating_value_radio_obj[i].value;
        }
    }
    $("votes").innerHTML = "<img src=\"/images/ajax-loader.gif\"/> Loading...";
    callVoteAjaxCall('votes','layouts/vote','votes',rating_type,ratable_id,rating_value,ratable_type) ;
    Element.hide("voter");
    Element.show("vote_thank_you");
}

function callVoteAjaxCall(div,partial,localvar,rating_type,ratable_id,rating_value,ratable_type,classes) {
    new Ajax.Updater(div, '/vote', {asynchronous:true, method:'post', postBody:'localvar=' + escape(localvar) +'&partial=' + escape(partial) +'&rating_type=' + rating_type + '&ratable_id=' + ratable_id + '&rating_value=' + rating_value + '&ratable_type=' + ratable_type + '&classes=' + classes});
}

function addCodeToFunction(func,code){
    if(func == undefined)
		return code;
    else{
		return function(){
			func();
			code();
		}
    }
}

function move_ad_sense() {
	var ad_content = $('sponsored');
	var ad_container = $('ad_sense_container');
	if (ad_content && ad_container) {
		ad_content.parentNode.removeChild(ad_content);
		ad_container.parentNode.replaceChild(ad_content, ad_container);
	}
}

function move_ad(holder, temp) {
	var ad_content = $(holder);
	var ad_container = $(temp);
	
	if(ad_content && ad_container) {
		ad_content.appendChild(ad_container);
		ad_container.show();
	}
}

function set_roundup_item_subtype(item_type_div, roundup_subtype) {
    if ($(item_type_div))   {
        $(item_type_div).value = roundup_subtype;
        //alert( eval(roundup_subtype + "_titles")  );
        update_autocomplete_arrays( eval(roundup_subtype + "_titles") );
    }
}

function update_autocomplete_arrays(arr) {
    for (i=0 ; i < 10; i++) {
        eval ("listing_title_" + i + "_auto_complete_var.options.array = arr;" )
    }
}

function pre_init_autocomplete_arrays(radioObj) {
    if(!radioObj)
		return ;
    var value;
    var radioLength = radioObj.length;

	for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
			value = radioObj[i].value;
		}
	}
    if(value==undefined) return;
    else
        update_autocomplete_arrays(eval(value + "_titles"));
}

function showMultipleMatches(related_items_map,related_items_geo_map,key,div) {
    var html_text = "";
    var  related_items;
    var related_items_geographies;
    if( related_items_map != undefined ) {
        related_items = eval("related_items_map." + key);
     }
    if( related_items_geo_map != undefined ) {
        related_items_geographies = eval("related_items_geo_map." + key);
     }
     if(related_items != undefined) {
        for (i=0; i < related_items.length ; i++) {
            var item = related_items[i];
            if(item != undefined) {
                html_text = html_text + "<a href=\"javascript:void\" onClick=\"Element.hide('" +div + "');";
                html_text = html_text + "document.getElementById('" + key +"_id').value='" + item.attributes.id + "' ;\">" ;
                html_text = html_text + item.attributes.title +", " ;
            }
            if (related_items_geographies != undefined) {
                var geography =  related_items_geographies[i];
                if (geography != undefined) {
                    html_text = html_text + geography.attributes.name +  "</a><br>"
                }
            }
            //alert (html_text);
        }
    }
    var div_element = document.getElementById(div);
    if(div_element!=undefined) {
        div_element .innerHTML = "<b>Multiple Matches Found !! </b> <br>" + html_text;
    }
}


/*
 yun's validation.. refs #1055
 
function checkDuplicateItemTitles() {
    if(arguments[0] != undefined)   {
        currId =  arguments[0].id;
        var idObj = eval(document.getElementById(currId + "_id"));
        idObj.value = "";
    } else {
        currId = "";
    }
    var params = Form.serialize('lists_form') + "&curr_element=" + currId ;
    if   (currId == "") {
        new Ajax.Request('/lists/check_duplicate_item_titles?' + params,
            {   asynchronous:false, evalScripts:true,
                onComplete:function(request){eval(request.responseText)}});

    }   else {
        new Ajax.Request('/lists/check_duplicate_item_titles?'+ params,
            {   asynchronous:true, evalScripts:true,
                onComplete:function(request){eval(request.responseText)}});
   }
}

 
 
function formCheckDuplicateItemTitles(action) {
    $('lists_action').value=action
    checkDuplicateItemTitles() ;
    if(document.getElementById("lists_form").multiple_found.value=="true")   {
    } else {
        document.getElementById('lists_form').submit();
    }
}*/

function deleteTitleIds() {
    for(i=0;i<9;i++) {
        var idObj = eval(document.getElementById("listing_title_" + i + "_id"));
        idObj.value = "";
    }
}

function open_flyout(flyout_id) {
	
      $$('.flyout').each(function(match){
	       Element.hide(match.id);
	   });   
        divPopup=document.getElementById(flyout_id);	
        if (isIE()) {
			if (g_PopupIFrame != null) {
				document.body.removeChild(g_PopupIFrame);
				g_PopupIFrame = null;
			}
			//Increase default zIndex of div by 1, so that DIV appears before IFrame
			//divPopup=document.getElementById(flyout_id);
			divPopup.style.zIndex = divPopup.style.zIndex + 1;
			
			var iFrame = document.createElement("IFRAME");
			g_PopupIFrame = iFrame;
			iFrame.setAttribute("src", "");
			
			divPopup.style.display = "block";
			
			//Match IFrame position with divPopup
			iFrame.style.position = "absolute";
			iFrame.style.left = divPopup.offsetLeft + 'px';
			iFrame.style.top = divPopup.offsetTop + 'px';
			iFrame.style.width = divPopup.offsetWidth + 'px';
			iFrame.style.height = divPopup.offsetHeight + 'px';
			
			//Store iFrame in global variable, so it can get removed when divPopup is hidden g_PopupIFrame=iFrame;
			g_PopupIFrame = iFrame;
			
		}
		else {
			divPopup.style.display = "block";
		}	
}

function change_venue_map(slug, selection_options) {  
  var selected = null;
  for(var i=0;i<selection_options.options.length;i++) {
    if(selection_options.options[i].selected) {
      new Ajax.Request('/maps/show_venue_markers/'+slug+'/'+selection_options.options[i].value, {asynchronous:true, evalScripts:true, method:'get', onComplete:function(request){eval(request.responseText)}});
      break;
    }
  }
}

function open_facet_flyout(flyout_id) {    
    var cont=new Array();
	for(var i=0,j=0;i<facet_flyouts.length;i++)
	{var x=document.getElementById(facet_flyouts[i]);	
	 if (x)
	  {cont[j]=x;
	  j++;}
	}
	  for(var i=0;i<cont.length;i++){		
		 cont[i].style.display="none";        
    }
	Element.show(flyout_id);
	
	
	
	
}
                 

function updateCalNav(element) {              
    for (i=0;i<8;i++) {Element.removeClassName('cnb_'+i,'selected');}
    Element.addClassName(element,'selected');
}
var updateListingFormDisabled = false;

function toggle_update_listing_form()
{
	if (updateListingFormDisabled) {
		Form.enable('update_listing_form');
		updateListingFormDisabled = false;
	} else {
		updateListingFormDisabled = true;
		Form.disable('update_listing_form');
		$('update_listing_closed').disabled = false;
		$('update_listing_submit').disabled = false;
	}
}


function checkDuplicateItemTitles() {
	var detected="";
    if(arguments[0] != undefined)   {
        currId =  arguments[0].id;
        var idObj = eval(document.getElementById(currId + "_id"));
        idObj.value = "";
    } else {
        currId = "";
    }

    var params = Form.serialize('lists_form') + "&curr_element=" + currId ;
    new Ajax.Request('/lists/check_duplicate_item_titles?'+ params,
            {   asynchronous:false, evalScripts:true,
                onComplete:function(request){detected=request.responseText;}});
	return detected;

}

function validate_listing(action)
{
	
	var error_msg_div = document.getElementById('error-messages');
    var listing_title=$F('list_headline');
	var listing1=$F('listing_title_0');
	var listing2=$F('listing_title_1');
	var listing3=$F('listing_title_2');
	var errors = false;
    var msg = '';
     

    if (listing_title=="" ) {
        msg = msg + "<li>List name required</li>";
        errors = true;
    } 
	
	if (listing1=="" || listing2=="" || listing3=="" || listing1=="name" ||listing2=="name" || listing3=="name" ) {
        msg = msg + "<li>First 3 items required</li>";
        errors = true;
    }  

    if (!errors) {
        if (detect_profanity()) {
            msg = msg + "<li>List fields cannot contain profanity</li>";
            errors = true;
        }
		duplicate_msg=checkDuplicateItemTitles();
		if(duplicate_msg=="false")
		{ errors=false;
		 }
		else{msg = msg + "<li>"+duplicate_msg+"</li>";
             errors = true;} 
    }
	
    if (msg!='') {
        msg='<ul class="error_messages">'+msg+'</ul>';		
    }
    error_msg_div.innerHTML = msg;
    $('lists_action').value=action;
    if(!errors)
	{   
		clearListing();		
		$('lists_action').value=action;
		document.getElementById('lists_form').submit();
	}
	else{
		 window.location.hash='#start';
       //document.getElementById('error-messages').focus();
    }
}



function clearListing()
{ 
  var cont=new Array();
  cont=$('lists_form').getElementsByTagName('input');
  for(i=0;i<cont.length;i++){
       if (cont[i].value=="name" || cont[i].value=="description")     
	   {cont[i].value="";}   
     }
	
}

function clearListingTitle(title)
{
 var cont = $(title);
 if ( cont.value=="name" )
       cont.value="";	
}

function clearListingDescription(description)
{
 var cont = $(description);
 if ( cont.value=="description" )
       cont.value="";	
}

function detect_profanity(){
    var check_text = $F('list_headline');
    for (var i=0; i<10; i++) {
        var title_text = $F('listing_title_'+i);
        if (title_text!='' && title_text!='name') check_text=check_text+' '+title_text
        var desc_text = $F('listing_description_'+i);
        if (desc_text!='' && desc_text!='description') check_text=check_text+' '+desc_text
    }
    var detected = '';
    new Ajax.Request('/lists/detect_profanity?fields='+encodeURIComponent(check_text),
        {   asynchronous:false, evalScripts:true,
            onComplete:function(request){detected = request.responseText}});
    if (detected=='true')
        return true;
    else
        return false;
}

function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) {
	var sCookie = sName + "=" + encodeURIComponent(sValue);
	if (oExpires) {
		sCookie += "; expires=" + oExpires.toGMTString();
	}
	if (sPath) {
		sCookie += "; path=" + sPath;
	}
	if (sDomain) {
		sCookie += "; domain=" + sDomain;
	}
	if (bSecure) {
		sCookie += "; secure";
	}
	document.cookie = sCookie;
}

function getCookie(sName) {
	var sRE = "(?:; )?" + sName + "=([^;]*);?";
	var oRE = new RegExp(sRE);
	if (oRE.test(document.cookie)) {
		return decodeURIComponent(RegExp["$1"]);
	} else {
		return null;
	}
}

function deleteCookie(sName, sPath, sDomain) {
	setCookie(sName, "", new Date(0), sPath, sDomain);
}

profileIE6SubnavHover = function() {
	$$('.profile-nav .subnav').each(function(subnav) {
		subnav.onmouseover = function() { this.addClassName('hover'); }
		subnav.onmouseout  = function() { this.removeClassName('hover'); }
	}); 
}
if (window.attachEvent) window.attachEvent("onload", profileIE6SubnavHover);

