var remove_location = function(id){
	$.getJSON('/api',
		{
			'method': 'Location.remove',
			'locationId': id,
			'e_id': window.e_id
		},
		function(data){
			if ( data.success == 1){
				$('.location_' + data.locationId).remove();
			}else{
				alert('there was a problem');
			}
	});
}

$(document).ready(function() {
				
	$('.login-nav-settings').hover(function(){
		if ( $('.login-nav-settings-menu:hidden') ) {
			$('.login-nav-settings').toggleClass('hoverstate').children('.login-nav-settings-menu').toggle();
			$('.login-nav-settings-arrow').toggleClass('color5');
		}
	});
	
	//when form is submitted, if search type is not events, remove date from url
	$('form.search-form').submit(function(){
	  if( ($('.searchingForText').text() != 'Events') || ($('#search_by_date_active').val()!=1) ) {
	    $('#search_by_date').val('');
	    
	  }
	});
	if( $(".search-form").length > 0 ){
	    var default_search_text = "Search"
		var search_input_text = (window.search_term.length > 0) ? window.search_term : default_search_text;
	}

    // This is the location switcher js
	$('.location-switcher .current-location').click(function(){
        $sw = $('.location-switcher');
        if($sw.hasClass('hoverstate')) {
            $sw.children('.change-location').addClass('hide');
            $sw.removeClass('hoverstate');
            $sw.children('.change-location').css({"z-index":0});
        } else {
            $sw.children('.change-location').removeClass('hide');
            $sw.addClass('hoverstate');
            $sw.children('.change-location').css({"z-index":10010});
        }

		//$sw.toggleClass('hoverstate');
		$("#id_location").focus();
	});
	
	$(document).click(function(){
		$('.location-switcher').removeClass('hoverstate');
        $('.location-switcher').children('.change-location').addClass('hide');
        $('.location-switcher').children('.change-location').css({"z-index":0});
	});
	$('.location-switcher').click(function(e){
		e.stopPropagation();
	});
	var default_location_text = $('.location-switcher #id_location').val()
	$('.location-switcher #id_location').focus( function() {
		if($(this).val() == default_location_text){
			$(this).val('');
		}
	});
	$('.location-switcher #id_location').blur( function () {
		if($(this).val() == ''){
			$(this).val(default_location_text);
		}
	});
	
	$('.delete-location').click(function() {
		$(this).parent('li').fadeOut();
	});

	$('.id_location').focus( function () {
		if($(this).val() == window.geo_location){
			$(this).val('');
		}
	});

	$('.id_location').blur( function () {
		if($(this).val() == ''){
			$(this).val(window.geo_location);
		}
	});
    // End location switcher js
    
    
    //grab variables from url
    var urlParams = {};
    (function () {
        var e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = window.location.search.substring(1);

        while (e = r.exec(q))
           urlParams[d(e[1])] = d(e[2]);
    })();

    //search by date functions
    
    //this allows the search by date bar to close and animates the search input fields
    var search_by_dateClose = function()
    {
		$('#search_by_date_display_container').slideUp('fast'); //hide the search by date stuff
		$('#search').animate({marginLeft:'27px',width:'170px'}, { duration: 500, queue: false });
    	$('#search_by_date_status').animate({width:'28px'}, { duration: 500, queue: false });
    	$('#search_by_date_status .inner').animate({left:'-50px'}, { duration: 500, queue: false });
    	$('#search_by_date_icon').attr('src','http://s3.amazonaws.com/wimgo/images/wimgo-search-date-popup-icon.gif');
    	$('#search_by_date_active').val('0');
    }
    
    $(function() {
      $('#search_by_date_status').click(function(e){
       
        if($('#search_by_date_display_container').is(":visible"))
        {
        	search_by_dateClose();
        } 
        else 
        {
			$('.searchingForText').text('Events');
			$('.search-form .selected').removeClass('selected');
			$('.search-form a[rel=events]').parent().addClass('selected');
			var parts = $('.search-form').attr('action').split('/');
			parts[parts.length-2] = 'events';
			$('.search-form').attr('action', parts.join('/') );
			$('#search_by_date_display_container').slideDown('slow');
			$('#search_by_date_icon').attr('src','http://s3.amazonaws.com/wimgo/images/wimgo-search-date-close-icon.gif');
        }
      });
     
      $sbdd = $('#search_by_date_display');
      if ($sbdd.length) {
			$sbdd.datepicker({
			    defaultDate: urlParams["search_by_date"],
				altField: "#search_by_date",
				minDate:0,
				onSelect: function(dateStr) {
				
					$('#search_by_date_status_month').text($.datepicker.formatDate('M', $(this).datepicker('getDate')));
					$('#search_by_date_status_day').text($.datepicker.formatDate('d', $(this).datepicker('getDate')));
					$('#search_by_date_status_year').text($.datepicker.formatDate('yy', $(this).datepicker('getDate')));
					$('#search_by_date_icon').attr('src','http://s3.amazonaws.com/wimgo/images/wimgo-search-date-popup-icon.gif');
				  	
				  	$('#search_by_date_display_container').slideUp('slow', function() {
				  	
				  		if(!$('#search_by_date_clear').hasClass("hide"))
				  		{
							$('#search_by_date_status').animate({width:'82px'}, 500);
            				$('#search_by_date_status .inner').animate({left:'23px'}, 500);
            				$('.search-input').animate({marginLeft:'81px',width:'117px'},500).focus().effect("highlight", {}, 3000);
				  		}
	       			});
        			
          			$('#search_by_date_clear').removeClass('hide').click(function(){
						$('#search_by_date_display').datepicker('setDate',null);
						search_by_dateClose();
						$(this).addClass('hide');
					});
					
					$('#search_by_date_active').val('1');	
				}
			});
							
		}
    });

    //End search by date
    

	$('.searchingForBox').click(function(){
		$('.search-form .drop').toggleClass('hoverstate');
		//search_by_dateClose();
	});

	$(document).click(function(){
		$('.search-form .drop').removeClass('hoverstate');
	});

	$('.searchingForBox').click(function(e){
					e.stopPropagation();
	});

	$('.search-input').focus( function () {
	    if( $(this).val() == default_search_text){
		    $(this).val('');
        } else {
            $(this).select();
	    }
	});

	$('.search-input').blur( function () {
		if($(this).val() == ''){
		//	$(this).val(search_input_text);
		}
	});

	$('a.single-search-filter').each( function(){
		$(this).bind('click', function(){
			$('.search-form .selected').removeClass('selected');
			$('.search-form .drop').removeClass('hoverstate');
			$(this).parent().addClass('selected');

            var parts = $('.search-form').attr('action').split('/');
            parts[parts.length-2] = $(this).attr('rel');

            $('.search-form').attr('action', parts.join('/') );

			$('.searchingForText').html($(this).text() );
			$('.searchingForBox').slideDown("slow");
			$('.search-input').focus();
			
			if($(this).text() != "Events")
			{
	        	search_by_dateClose();
			}
			
			return false;
		});
	});

	$(".printOffersLink").click(function () {
		if ($(this).hasClass("nothingToPrint")){
			alert("There is nothing to print. Please add one or more deals to your wallet, then try again.");
			return false;
		}
	});
	
	if($(".onoff")){
		$(".onoff").live('click',function() {
			if( $(this).find("input").attr("checked") == "" || $(this).hasClass("active") ) {
				$(this).find("input").attr("checked", true).
					siblings(".onoff").find("input").attr("checked", false);
				$(this).addClass("active").
					siblings(".onoff").removeClass("active");
			} else {
				$(this).find("input").attr("checked", false).
					siblings(".onoff").find("input").attr("checked", true);
				$(this).removeClass("active").
					siblings(".onoff").addClass("active");
			}
		});
	}
	
	/*if($(".recommendations")){ //comenting yahoo stuff
		$(".recommendations a").click(function(){
			ywa_onclick("Recommended Events: " + $(this).attr('title'), "Events", "INTERNAL_SEARCH");
			});
	}*/
	
	
	if($("input#cpassword")){
		$("input#cpassword").blur(function(){
			if($("input#cpassword").val() != $("input#rpassword").val() ) {
				$(this).siblings('.error').remove();
				$(this).after("<span class='alert-result color2'>Passwords do not match. Please enter again.</span>");
			} else {
				$(this).siblings('.error').remove();
			}
		});
	}
	
	
	if( jQuery('.item-management').length>0 ) {
		jQuery('.item-management').parent().hover( function() {
			jQuery(this).children('.item-management').show();
		}, function() {
			jQuery(this).children('.item-management').hide();
		});
	}
	
	
	if( jQuery('#twitterformslide').length>0 ) {
		$('#twitterformslide').hide();
		$('#twitterformslidelink').click( function(){ $('#twitterformslide').slideToggle(); return false; });
		$('#twitter-suggest input[type=submit]').after('<a id="twittersubmitbutton" class="button button-primary"><span> Submit </span></a>').hide();
		$('#twittersubmitbutton').click( function() { if( $.trim($('#twitter-username').val())!= ''){ $('#twitter-suggest').submit();} return false;});
		$('#twitter-suggest').submit(function() {
			
			$('#twittersubmitbutton span').text("Sending...");
			$.post('twitterlist/save',{username: $('#twitter-username').val() },
			
			function(data){
				if(data.success) {
					$('#twitter-suggest').after('<p><img class="f-left" src="http://s3.amazonaws.com/wimgo/images/twitterBird.gif" alt="twitter icon" />&nbsp;&nbsp;Thank you for your submission.</p>').hide();
			
				} else {
					console.log(data);
				}
			}, "json");
			return false;
		});	
	}


	if($(".sevenday").length > 0){
			function mycarousel_initCallback(carousel) {
			    jQuery('.sevenday .jcarousel-control li').bind('click', function() {
					jQuery(this).addClass("selected");
					jQuery(this).siblings().removeClass("selected");
					jQuery(this).children(".weekday, .monthday").fadeIn("fast");
			        activePanel = $(this).children('.count').text();
			        $('.sevenday .jcarousel-item').siblings().removeClass('activePanel');
			        $('.sevenday .jcarousel-item[jcarouselindex='+activePanel+']').addClass('activePanel');
			        $('.sevenday .carousel').height( $('.activePanel').height() + "px" );
			        
			        //GOOGLE ANALYTIC TRIGGER : 3.15.2011 rJONES
			        if (_gaq) {_gaq.push(['_trackEvent', 'EVENTS PAGE', '7-DAY CAROUSEL', activePanel]);}
			    });
			};
			
			jQuery(document).ready(function() {
			
				// Ride the carousel...
			    jQuery(".sevenday .carousel").jcarousel({
			        scroll: 1,
			        initCallback: mycarousel_initCallback,
			        buttonNextHTML: null,
			        buttonPrevHTML: null
			    });
			    $('.sevenday .carousel').height( $('.jcarousel-item[jcarouselindex=1]').height() + "px" );
			    
			});
	}

	$("input.error-alert").blur( function () {
	    if( $(this).val() != "" && $(this).val() != "Invalid E-mail Address"){
		    $(this).removeClass("error-alert").next(".alert-result").hide();
	    }
	});

	
	//handles switching from now showing to coming soon carousels
	$('.tabs>ul.tab-control>li>a').click( function () {
		
		$('.tabs>ul.tab-control>li').removeClass("active"); //remove active from all tabs
		$(this).parent().addClass("active"); //add active to the list element above this a link
		$('.tabs>.tab-content').addClass("hidden"); //hide all content panes
		var id = "#"+this.href.split('#')[1]; //parse href to determine which id to show
		$(id).removeClass("hidden"); //reveal the pane that matches the tab clicked
		
		return false;
	});

    // new tab style
	// handles switching from now showing to coming soon carousels
	$('.tabs-v2>ul.tab-control-v22>li>a').click( function () {
		
		$('.tabs-v2>ul.tab-control-v2>li').removeClass("active"); //remove active from all tabs
		$(this).parent().addClass("active").addClass("bg-color0"); //add active to the list element above this a link
		$('.tabs-v2>.tab-content').addClass("hidden"); //hide all content panes
		var id = "#"+this.href.split('#')[1]; //parse href to determine which id to show
		$(id).removeClass("hidden"); //reveal the pane that matches the tab clicked
		
		return false;
	});

	if($(".toggle-link")){
    	$(".toggle-link").click(function(){
    			$(this).next(".toggle-container").slideToggle();
    			$(this).children(".toggle-arrow").toggleClass("toggle-open");
    	});
	}
	
	if($(".business-category-landing")){
				var total_rows = jQuery('div.row').size();
			
				var current_row = 0;
				var next_row = current_row+1;
				var prev_row = -1;
			
				function createPages(){
					for(i = 1;i < total_rows+1;i++){
						current = "";
						
						if(i == 1){
							current = " class='currentPage'";
						}
						jQuery('.pages').append("<li"+current+"><a class='color9' href='javascript:void(0)'>"+i+"</a></li>");
					}
				}
			
				jQuery("#next").click(function(){
					if(next_row >= total_rows){
					} else {
					
						jQuery("div.row").hide();
						jQuery("div.row:eq("+next_row+")").show();
			
						jQuery(".pages li").removeClass("currentPage");
						jQuery(".pages li:eq("+(current_row+1)+")").addClass("currentPage");
			
						prev_row = current_row;
						current_row = next_row;
						next_row = next_row+1;
						
						endCheck();
			
					}
				});
			
				jQuery("#prev").click(function(){
					if(prev_row < 0){
					} else {
			
						jQuery("div.row").hide();
						jQuery("div.row:eq("+prev_row+")").show();
				
						jQuery(".pages li").removeClass("currentPage");
						jQuery(".pages li:eq("+(current_row-1)+")").addClass("currentPage");
						
						next_row = current_row;
						current_row = prev_row;
						prev_row = prev_row-1;
						
						endCheck();
			
					}
				});
					
				jQuery(".pages li a").live("click", function(){
					jQuery(".pages li").removeClass("currentPage");
					jQuery(this).parent().addClass("currentPage");
					
			
					current_row = jQuery(this).text();
					current_row = current_row-1;
					jQuery("div.row").hide();
					jQuery("div.row:eq("+current_row+")").show();
					
					prev_row = current_row-1;
					next_row = current_row+1;
					
					endCheck();
				});
			
				function endCheck(){
					if(current_row == 0){
						jQuery("#prev").hide();
					} else {
						jQuery("#prev").show();
					}
					if(current_row+1 >= total_rows){
						jQuery("#next").hide();
					} else {
						jQuery("#next").show();
					}
				}
				
				createPages();
				endCheck();
				
	}

	
	if($(".toggle-controls")){
		$(".toggle-controls").children().click(function(){
			var current = $(this).closest('.toggle-controls').children().index(this);
			$(this).addClass("active").siblings().removeClass("active");
			$(this).closest(".mod").find(".toggle-item").hide().eq(current).show();
			if($(this).closest(".mod").find(".toggle-item").eq(current).children(".photo-carousel:not(.loaded)").length > 0 ) {
				$(this).closest(".mod").find(".toggle-item").eq(current).children(".photo-carousel:not(.loaded)").jcarousel({initCallback: photocarousel_initCallback,scroll:4});
				$(this).closest(".mod").find(".toggle-item").eq(current).children(".photo-carousel:not(.loaded)").addClass('loaded');
			}
			if($(this).closest(".mod").find(".toggle-item").eq(current).children(".video-carousel:not(.loaded)").length > 0 ) {
				$(this).closest(".mod").find(".toggle-item").eq(current).children(".video-carousel:not(.loaded)").jcarousel({initCallback: videocarousel_initCallback,scroll:1});
				$(this).closest(".mod").find(".toggle-item").eq(current).children(".video-carousel:not(.loaded)").addClass('loaded');
			}
		});
	}


	/*Yahoo Analytics - Page View //comenting yahoo stuff
	ywa_view(yahoo_document_name,yahoo_document_group);
	
	//Yahoo Analytics - Track Add Tags
	$(".button-add-tags").click(function(){  
		ywa_onclick("Add tags", yahoo_document_group, "INTERNAL_SEARCH");
	});
	*/

});

/* Yahoo Analytics Globals //comenting yahoo stuff
function ywa_view(yahoo_document_name,yahoo_document_group) {
	var YWATracker = YWA.getTracker("10001343081630");
	YWATracker.setDocumentName(yahoo_document_name);
	YWATracker.setDocumentGroup(yahoo_document_group);
	YWATracker.submit();
}
function ywa_impression(name) {
	var YWATracker = YWA.getTracker("10001343081630");
	YWATracker.setDocumentName(yahoo_document_name);
	YWATracker.submit();
}
function ywa_onclick(name,group,action) {
	var YWATracker = YWA.getTracker("10001343081630");
	YWATracker.setDocumentName(yahoo_document_name);
	YWATracker.setDocumentGroup(yahoo_document_group);
	YWATracker.setAction(action);
	YWATracker.submit();		
}
function ywa_featured_onclick(actionnumber,cfvalue) {
	var YWATracker = YWA.getTracker("10001343081630");
	YWATracker.setAction(actionnumber);
	YWATracker.setCF(17,cfvalue);
	YWATracker.submit_action();
}
*/
//GLOBAL ANALYTIC EVENT TRIGGER (GOOGLE/YAHOO) : 3.15.2011 rJONES
function trackClickEvent(t_category,t_name,t_action) {
	if (!t_action) {t_action="clicked";} //CATCH BLANK ACTION	
	if (_gaq) { _gaq.push(['_trackEvent', t_category, t_name, t_action]); } //GOOGLE TRIGGER	
	/*if (YWA) { ywa_onclick(t_name,t_category,t_action); } //YAHOO TRIGGER*/ //comenting yahoo stuff
}

jQuery.fn.repeat = function(times, string) {
    //For each item matched
    this.each(function(){
        var buff = string;
        for(var i=1; i < times; i++){
            buff += string;
        }
        jQuery(this).append(buff);
    });
    return this;
}


function toggleDiv() {
    for(i=0,c=arguments.length;i<c;i++){
        var theDiv = document.getElementById(arguments[i]);
        if(typeof theDiv == 'object')
            theDiv.style.display = (theDiv.style.display != 'none' ? 'none' : '' );
    }
}
function toggleReplies(id) {
    var me = document.getElementById(id);
    me.className = (me.className != "repliesButton open f-left" ? "repliesButton open f-left" : "repliesButton f-left");
}


function getDirections(start,end){
//    new Ajax.Request("/ajax/okla365/directions.php?start="+escape(start)+"&end="+escape(end));
    url = "http://maps.google.com/maps?f=d&hl=en&geocode=&time=&date=&ttype=&saddr="+escape(start)+"&daddr="+escape(end)+"&sspn=0.276491,0.752563&ie=UTF8&z=11&om=1";
    window.open(url,"directions","toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes");

}



//Object Oriented id names for jQuery effects
function textToggle(target,degrees) {
    degrees = degrees || 180;
	if ( $(target).is(":contains('more')") || $(target).is(":contains('More')") ) {
		$(target).html( $(target).html().replace("more","less").replace("More","Less") );
	} else {
		$(target).html( $(target).html().replace("less","more").replace("Less","More") );
	}
	$(target).find(".unicon").toggleClass("rotate" + degrees);
	//if ( $(target).is(":contains('&#9660;'), :contains('&#9650;'), :contains('?'), :contains('?')") ) {
	//	$(target).find(".unicon").toggleClass("rotate180");
	//}
}
$('[id*=toggle-]').live('click',function() {
	textToggle(this);
	var container = $(this).attr("id").replace("toggle-","");
	$('#'+container).toggle();
	return false;
});
$('[id*=slide-]').live('click',function() {
    var degrees = parseInt( $(this).attr("id").split(/-degrees/i)[1] );
	textToggle(this,degrees);
	
	var container = $(this).attr("id").replace("slide-","").replace(/degrees[0-9]+/,"");
	$('#'+container).slideToggle();
	return false;
});
$('[id*=fade-]').live('click',function() {
	textToggle(this);
	var container = $(this).attr("id").replace("fade-","");
	if ($('#'+container) .is(':hidden')) {
		$('#'+container).fadeIn();
	} else if ($('#'+container) .is(':visible')){
		$('#'+container).fadeOut();
	}
	return false;
});


function ieWarning() {
	$.jGrowl.defaults.setCookie = 'IE6';
	$.jGrowl.defaults.position = 'center';
	$.jGrowl.defaults.closeTemplate = 'x<div class="ie6-notification-closer">No thanks, I&#39;ll take my chances</div>';
	$.jGrowl("<h1 class='color9'>It's time to upgrade</h1>"+
		"<p class='color9'>When Internet Explorer 6 was created in 2001, it was cutting edge. The internet has changed a lot since then, and the tools that modern websites (like Google, Amazon and wimgo) use weren&#39;t even imagined back then. Wimgo no longer supports Internet Explorer 6, so you might not be getting the most out of the site. Please take a few minutes to upgrade your browser to something faster, safer and more enjoyable</p>"+
		"<span class='color9 browser-ie8'><p><b>Internet Explorer 8</b><br/>A familiar friend<br/><br/><a href='http://www.microsoft.com/windows/internet-explorer'class='button-flat'><span>Download Now</span></a></p></span>"+
		"<span class='color9 browser-firefox'><p><b>Mozilla Firefox</b><br/>Secure and stable<br/><br/><a href='http://mozilla.com/firefox' class='button-flat'><span>Download Now</span></a></p></span>"+
		"<span class='color9 browser-chrome'><p><b>Google Chrome</b><br/>Fast and friendly<br/><br/><a href='http://google.com/chrome' class='button-flat'><span>Download Now</span></a></p></span>"+
		"<p class='clear'></p>", {
        sticky: true,
        theme: "notification-banner hdr-font ie6-notification",
        close: function(e,m,o) {
            $.cookie('IE6', 'closed', { expires: 365, path: '/' });
        }
    });
}

// jGrowl topbar notification
function topBar(msg,theCookie,isSticky) {
    theCookie = theCookie || "";
    isSticky = isSticky || true; // Default sticky as true unless arg is passed as false
    $("#topbar").jGrowl(msg, {
        animateOpen: {height: 'show'},
        animateClose: {height: 'hide'},
        life: 10000,
        sticky: isSticky,
        theme: "jGrowl-reset topbar topbar-postit",
        close: function(e,m,o) {
            $.cookie(theCookie, 'closed', { expires: 365, path: '/' });
        }
    });
}

