// 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
}

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

$.fn.toggleNews = function() {

    $(".news-handle").siblings('div').hide();

    $(".news-handle").click(function(e){

        $(e.target).siblings('div').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
        var tipTitle = Taubman.translate('Add to My ' + ucfirst(type) + 's');
        var tipText  = Taubman.translate('Click the "+" icon to indicate your favorite ' + type + 's for easy access and personalized browsing');
        $("body").append("<div id='tooltip'><h4>" + tipTitle + "</h4><p>" + tipText + "</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 = Taubman.translate('Successfully Added');
            url  = '/my_profile';
            break;
        case 'Invalid request':
        default:
            // display some "My bad" message
            text = Taubman.translate('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 = Taubman.translate('My Profile');
            url  = '/my_profile';
            break;
        default:
            // display some "My bad" message
            text = Taubman.translate('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, .relocated").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;
}

// ImagesLoaded Plugin
//
// @see https://gist.github.com/268257
//
// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images
//
// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!
//
// callback function is passed the last image to load
// as an argument, and the collection as `this`
//
$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
  elems.bind('load.imgloaded',function(){
      if (--len <= 0 && this.src !== blank){
        elems.unbind('load.imgloaded');
        callback.call(elems,this);
      }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }
  });
  return this;
};

////////////////////////////////////////////////////////
//DOC READY
////////////////////////////////////////////////////////

var Taubman = {};

$(document).ready(function() {

    Taubman.lang = $('html').attr('lang');
    if (Taubman.lang != '' && Taubman.lang != 'en') {
        $.ajax({ url: '/api/translate.asp', dataType: 'json', success: function (data) { Taubman.translations = data; } });
    }
    Taubman.translate = function (key) {
        if (typeof(Taubman.translations) != 'undefined'
            && typeof(Taubman.translations[Taubman.lang]) != 'undefined'
            && typeof(Taubman.translations[Taubman.lang][key]) != 'undefined') {
            return Taubman.translations[Taubman.lang][key];
        }
        return key;
    };

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

    $(".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.setDefaults($.datepicker.regional[Taubman.lang]);
    $(".datepicker").datepicker({ nextText: "&gt;", prevText: "&lt;", dateFormat: "mm/dd/yy" });

    $("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, #retail-employment dl dd, #jobs dl dd');
      }

    if ($('#cta').length == 0) {
        $('#static').show();
    }

});

