// Define console if it is not defined
// Also define the log function
// This should ensure forgotten console.logs don't cause
// pages to explode
if( typeof(console) === "undefined" ) {
    console = {};
    console.log = function(){}; // no-op
}


////////////////////////////////////////////////////////
//FONT REPLACEMENTS
////////////////////////////////////////////////////////

function fontreplace() {
	
	Cufon.replace("#info-business h1")("#shop h3")("#callout-bulletin h3")(".intro-profile p")(".store_card")("#event_date_form h3");

};

////////////////////////////////////////////////////////
//NEWS STORIES TOGGLE
////////////////////////////////////////////////////////

$.fn.toggleNews = function() {
	
	$(".news-handle").siblings().hide();
	
	$(".news-handle").click(function(e){
		
		$(e.target).siblings().slideToggle();
	
	})

};

////////////////////////////////////////////////////////
//CREATE TOOLTIPS FOR "ADD" BUTTONS
////////////////////////////////////////////////////////

function tooltip() {	
	
	$("a.add").hover(function(e){
		
		//find the location of the plus box
		var offset = $(this).offset();
		var xOffset = Math.round(offset.left);
		var yOffset = Math.round(offset.top);

        var type = "store";
        if( $(this).hasClass("favorite_event") ) {
            type = "event";
        }
        else if ( $(this).hasClass("favorite_offer") ) {
            type = "offer";
        }
		
		//add tooltip to the page		
		$("body").append("<div id='tooltip'><h4>Add to My "+ucfirst(type)+"s</h4><p>click the “+” icon to indicate your favorite "+type+"s for easy access and personalized browsing</p></div>");
		
		//place the tooltip based on location of the plus box
		$("#tooltip")
			.css("top", yOffset - 130 + "px")
			.css("left", xOffset - 121 + "px")
			.fadeIn("fast");		
    },
	
	function(){
		
		$("#tooltip").remove();
    });	
				
};

/////////////////////////////////////////////////////
/// UPPERCASE FIRST CHARACTER OF A STRING
////////////////////////////////////////////////////
function ucfirst(str) {
    return str.charAt(0).toUpperCase() + str.substr(1);
}

////////////////////////////////////////////////////////
//ADD FAVORITE STORE/EVENT/OFFER STUFF
////////////////////////////////////////////////////////

function addToFavorites( e ) {

    var link = this;
    var $link = $(link);

    if ($link.is(':not(a.add)')){ link = $link.siblings('a.add').get(0); }

    var type = e.data;
    var id   = link.id;
    var entity; // where / how do I get this

	//got rid of this because it doesn't allow user to click register when they're prompted 
    //e.preventDefault();
        
    jQuery.ajax({
        type:     'post',
        url:      '/add_favorite',
        data:     {type: type, entity: entity, id: id},
        dataType: 'json',
        context:  {link: link, type: type},
        success:  onFavoritesSuccess,
        error:    onFavoritesError
    });
    
}
    
function onFavoritesSuccess( data, status, xhr ) {
    var args = this;
    var link = args.link, $link = $(link);
    var type = args.type;
    var text = 'My profile';
    var url  = '/my_profile';

    var ucType = ucfirst(type);

    switch (data.message) {
        case 'Already favorited':
            // fall through
        case 'Success':
            text = 'Successfully Added';
            url  = '/my_profile';
            break;
        case 'Invalid request':
        default:
            // display some "My bad" message
            text = 'Log in to Add';
            url  = '/signin';
            break;
    }

    $link
    	.addClass("add-prompt").text(text).attr('href', url)
    	.parent().prevAll('dt:first').addClass('added');
    }
    
function onFavoritesError( xhr, status, error ) {
    var args = this;
    var link = args.link, $link = $( link );
    var type = args.type;
    var text = '';
    var url  = '';
    
//alert(error + "\n was the error and the xhr is \n" + xhr);
console.log(error + "\n was the error and the xhr is \n" + xhr);
    switch (error) {
        case 'SyntaxError: JSON.parse':
            text = 'My Profile';
            url  = '/my_profile';
            break;
        default:
            // display some "My bad" message
            text = 'Register';
            url  = '/register';
            break;
    }
    $link.addClass("add-prompt").text(text).attr('href', url);

}



////////////////////////////////////////////////////////
//ADD MY STORES FLAG
////////////////////////////////////////////////////////

$.fn.added = function() {
	
	//add tag image denoting MyStore
	$(".added, .sponsor-preferred, .sponsor-official, .new, .sale, .coming-soon").append("<span class='tag'></span>");

};

////////////////////////////////////////////////////////
//DIRECTORY FUNCTIONALITY
////////////////////////////////////////////////////////

function directory() {
	
	//store children of main directory holder
	var directories = $("#directory-holder > .directory");
		
	$("#directory-nav li a").click(function (){
	
		//add or remove active class from parent li
		$(this).parent().addClass("active");
		$(this).parent().siblings().removeClass("active");
		
		//find hash and animate in the corresonding div, or the full listing
		if(this.hash != "#all"){
		
			directories.slideUp().filter(this.hash).slideDown();
		
		} else {
		
			directories.slideDown();
		
		}
		
		return false;
		
	});
			
};

////////////////////////////////////////////////////////
//JQUERY UI AUTOCOMPLETE
////////////////////////////////////////////////////////

function autoComplete(config) {
    
    var defaults = {
            submit_form: false,
            char_len: 2,
            datasource: [],
            onSelect: function (event, ui) {
                if (settings.value_field) { $(settings.value_field).text(ui.item.value); }
                if (settings.id_field) { $(settings.id_field).val(ui.item.id); }
                if (settings.submit_form) {
                    if (ui.item.slug) {
                        var $form = $(settings.value_field).closest('form');
                        if (undefined == settings.orig_action) {
                            settings.orig_action = $form.attr('action').replace(/\/$/, '');
                        }
                        $form.attr('action',settings.orig_action+'/'+ui.item.slug);
                    }
                    $form.submit();
                }
            }
        },
        settings = $.extend(true, {}, defaults, config);

    $(settings.value_field).autocomplete({
        source:    settings.datasource,
        minLength: settings.char_len,
        select:    settings.onSelect
    });

};

////////////////////////////////////////////////////////
//CLEAR DEFAULT VALUES FOR INPUT FIELDS
////////////////////////////////////////////////////////

$.fn.cleardefault = function() {
	
	return this.focus(function() {
		
		if( this.value == this.defaultValue ) {
		this.value = "";
		
		}
		
	}).blur(function() {
			
		if( !this.value.length ) {
		this.value = this.defaultValue;
		
		}
		
	});
};
	
////////////////////////////////////////////////////////
//SET UP TABS
////////////////////////////////////////////////////////

var tabOpts = {

	fx: {
		opacity: "toggle",
		duration: "fast" 
	},
	
	select: function(event, ui){
		//console.log(ui.panel.id);
		var newURL = ui.panel.id
		document.location.hash = newURL;
	}
};

////////////////////////////////////////////////////////
//PROFILE STORES LIST
////////////////////////////////////////////////////////

$.fn.getStores = function() {
	
	var suggestList = $("ul#suggested-stores");
	var suggestItem = $("ul#suggested-stores li")
	var chosenList = $("ul#selected-stores");
	var submitList = $("fieldset#chosen-stores");
	
	$(suggestItem).click(function(){
		//add list item to other list
		$(chosenList).append(this);
		//$(this).unbind("click");
		
		//add value to hidden input
		var storeVal = this.id;
		var storeInput = "<input type='hidden' name='my-stores' style='display:none' value='" + storeVal + "' />"
		$(submitList).append(storeInput);
	});
	
	$("a.move-back").live("click", function(e){
	
		var moveItem = $(this).parent();
		var moveVal = moveItem.attr("id");
		var removeInput = $(submitList).find("input[value='"+ moveVal + "']");
		
		//remove items from fieldset and move back to other list
		$(suggestList).append(moveItem);
		$(removeInput).remove();
	});
		
};

////////////////////////////////////////////////////////
//CENTER STORE CARD TEXT
////////////////////////////////////////////////////////
$.fn.vAlign = function(container) {
		return this.each(function(i){
			if(container == null) {
				container = 'div';
			}
			$(this).html("<" + container + ">" + $(this).html() + "</" + container + ">");
			var el = $(this).children(container + ":first");
			var elh = $(el).height();
			var ph = $(this).height();
			var nh = (ph - elh) / 2;
			$(el).css('margin-top', nh);
		});
};

////////////////////////////////////////////////////////
//REMOVE ITEMS FROM PROFILE
////////////////////////////////////////////////////////
function deleteItem(){

	var itemParent = $(this).parent();
	var itemSibling = $(this).parent().prev();
	var itemID = $(itemSibling).attr("id");
	var itemTypeRaw = $(itemSibling).parent().parent().attr("id").split("-");
	var itemType = itemTypeRaw[1].slice(0, -1);
	var itemAfter = $(this).parent().next(); 
	var itemsCombined = itemParent.add(itemSibling).add(itemAfter);
	
	console.log(itemID + " " + itemType);
	
	$.ajax({
		type: "POST", 
		url: "/favorite/delete/" + itemType + "/" + itemID,
		//data: itemID,
		success: function(){
			itemsCombined.fadeOut("slow", function(){
				$(this).remove();
			});
		}
		
	});
	
	return false;
}
////////////////////////////////////////////////////////
//DOC READY
////////////////////////////////////////////////////////

$(document).ready(function() {

  	jQuery('body')
    .delegate('a.favorite_event', 'click', 'event', addToFavorites)
    .delegate('a.favorite_offer', 'click', 'offer', addToFavorites)
    .delegate('a.favorite_store', 'click', 'store', addToFavorites)
    ;

	fontreplace();
	
	$(".news-handle").toggleNews();

	$("input.clear-default").cleardefault();
	
	$(".added").added();
	$(".item-delete").bind("click", deleteItem);
	
	tooltip();
	
	directory();
	
	$("#tabs").tabs(tabOpts);
	
	$(".map-thumb").click(function() {
    	$("#tabs").tabs("select", "#map");
    	return false;
	});
	
	$("#profile-add-stores").getStores();
	
	$(".datepicker").datepicker({ nextText: "&gt;", prevText: "&lt;" });
	
	$("span.store_card").vAlign();
	
	$("input[type='hidden']").css({display:"none"});
	
	//browser fixes that css just couldnt handle
	if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
  		$('<span class="ie-rule" />').insertAfter('dl dd[class="util-links"]');
  		$('dl hr').hide();
  		$('<span class="ie-rule" />').insertAfter('dl.partners dd, #my-stores dl dd, #my-event dl dd, #my-offers dl dd');
  	}    
  			
});
