var favorites = {};

/**
 * dom elements used and method for working with the dom
 */
favorites.dom = {
    fav_sel_icon: '<div class="fav_sel_icon fav_sel_icon_'+lang+'" style=""></div>',
    fav_del_icon: '<div class="fav_del_icon fav_del_icon_'+lang+'"></div>',
    fav_widget_list: '#fav_widget_favlist',
    getId: function(str) { return str.substr(3); }, /* returns the raw id as dom elements must no start with numbers the ids and classes are prefixed with "id_" */
    getFavitemId: function(str) { return str.substr(8); } /* returns the raw id as dom elements must no start with numbers the favitem in the widget are prefixed with "favitem_" */
}

/**
 * ajax urls
 */
favorites.url = {
    remove: '/favorites/delete_favorite',
    add: '/favorites/add_favorite',
    exceed: '/favorites/exceeded',
    sort: '/favorites/sort_favorites'
}

/*
 *  dynamically add the favorite delete icon for the products that are
 *  currently in the product list.
 */   
favorites.addFavIcons = function()
{
	$('#fav_widget_favlist').children('li').each(function(index, Element){
        var id = favorites.dom.getFavitemId($(Element).attr('id'));

		$('#id_' + id).prepend(favorites.dom.fav_del_icon);
	});
}

/**
 * deletes a favorite item with the specified id with an ajax call
 * 
 * @param {Integer} id
 * @param {Dom-Element} caller
 */
favorites.deleteFavorite = function(id, caller) 
{
    $.ajax( {
        type: "POST",
        url: base_url + favorites.url.remove,
        data: "proId=" + id,
        dataType: "text",
        success: function(result) {
            favorites.deleteCleaner(true, caller);
        },
        error: function(result) {
            favorites.deleteCleaner(false, caller);
        }
    });
}


/*
 * cleans after the deletion process
 * 
 * @param {Boolean} status
 * @param {Dom-Element} caller
 * @return {Boolean} 
 */
favorites.deleteCleaner = function(status, caller) 
{
    if ($('#fav_widget_favlist').children('li'). length == 1) {
        $('#fav_widget_favmenu').children('li:not(.show_always)').fadeOut('slow');
        $('#fav_widget_trash').fadeOut('slow');
        $('#fav_widget_message').fadeIn('slow');
    }
    
    return status;
}



$().ready(function() {

	favorites.addFavIcons();

    /*
     * shows the 'add favorite icon' on mouseover 
     * and removes it on mouseout
     */
    $('.fav_sel').hover(
        function(e) {
            $(this).prepend(favorites.dom.fav_sel_icon);
        },
        function(e) {
            $(this).children('div.fav_sel_icon').remove();
        }
    );
	
	/*
	 * adds an hover effect for the boder of the surrounding anchor element
	 */
	$('div.fav_sel_icon, div.fav_del_icon').live('mouseover', function(e) {
        $('div.fav_add_border').removeClass('fav_pmborder');
		$(this).next('div.fav_add_border').addClass('fav_pmborder');
	});
	
	$('div.fav_sel_icon, div.fav_del_icon').live('mouseout', function(e) {
		$('div.fav_add_border').removeClass('fav_pmborder');
    });


    /*
     * adds an item to the favorites via ajax call, if successfull
     * the item is added to the favorites widget view
     */
    $('div.fav_sel_icon').live('click', function(e) {
		var self = $(this);
		var id =  favorites.dom.getId(self.closest('.fav_sel').attr('id'));
		
		self.removeClass('fav_sel_icon').addClass('fav_del_icon').addClass('fav_del_icon_' + lang);

		/*show hidden elements */
		$('#fav_widget_message').fadeOut('slow');
		$('#fav_widget_favmenu').children('li').fadeIn('slow');
		$('#fav_widget_favlist').fadeIn('slow');
        $('#fav_widget_trash').fadeIn('slow');

        $.ajax({
            type: "POST",
            url: base_url + favorites.url.add,
            data: "proId=" + id,
            dataType: "json",
            success: function(result) {
				    
				if (1 == result.status && $('#favitem_' + result.id).length == 0 ) {
					// @TODO:  check if ul already exists, if not create dynamically
					$('#fav_widget_favlist').append('<li class="fav_item" id="favitem_' + result.id + '"><a href="' + base_url + 'pmsht/' + result.href + '"><img src="' + result.src + '" /></a></li>');

				    var rand = Math.random().toString().substr(2);

				   /* show bubble */
				    $('.tooltip_left').fadeOut(150);
			        $('body').prepend('<div id="tooltip_'+rand+'" class="trans_dark tooltip_left" style="top: '+(e.pageY)+'px; left: '+(e.pageX - 215)+'px;"><div class="head round_topleft"></div><div class="head_img"></div><div class="body round_bottom"></div></div>');
			        $('#tooltip_'+rand+' > div.body').html(result.msg);
			        $('#tooltip_'+rand).fadeIn(300);
					
					window.setTimeout(function(){
						$('#tooltip_'+rand).fadeOut(300, function(){
							$(this).remove();
						});
					}, 4000);
					
				} else if(-1 == result.status) {
					self.removeClass('fav_del_icon').addClass('fav_sel_icon');
					dialog(target(base_url + favorites.url.exceed), 380, 200);
				}
            },
            error: function(result){
                self.removeClass('fav_del_icon').addClass('fav_sel_icon');
            }
        });
    });


    /*
     * deletes an item from the favorites list via ajax call
     */
    $('div.fav_del_icon').live('click', function(e){
        var self = $(this);
		var id = favorites.dom.getId(self.closest('.fav_sel').attr('id').toString());
		
        $('#fav_widget_favlist').children('#favitem_' + id).hide('slow', function() { 
            $(this).remove(); 
		});
		
        self.removeClass('fav_del_icon').addClass('fav_sel_icon');
		
		favorites.deleteFavorite(id, self);
    }); 


    /*
     * makes the list within the favorites widget sortable
     */
    $('#fav_widget_favlist').sortable( {
        opacity : 0.9,
        placeholder: 'placeholder',
        stop : function (element, ui) {
            if (drag == false) {
                var serial = $('#fav_widget_favlist').sortable('serialize');
                $.ajax({
                    url: base_url + favorites.url.sort,
                    type: "POST",
                    data: serial,
                    dataType: "text",
                    success: function(msg){},
                    error: function(msg){}
                });
            }
        
            drag = false;
        }
    });


    /*
     * disables the selection property (needed for sortable)
     */
    $('#fav_widget_favlist').disableSelection();
    

    /*
     * makes the trash droppable, accepting the favorites items
     */
    $('#fav_widget_trash').droppable({
        accept: '#fav_widget_favlist > li',
        activeClass: 'trash_highlight',
        drop: function(ev, ui) {
            drag = true; //set true to prevent sorting if item is dropped 
            id =  favorites.dom.getFavitemId(ui.draggable.attr('id'));
            ui.draggable.hide('slow', function() { $(this).remove(); } );
            $('#id_'+id).children('div.fav_del_icon').remove();
            favorites.deleteFavorite(id, ui.draggable);
        }
    });


	/* show tooltip */
	$('ul#fav_widget_favmenu > li > a > img').mouseover(function(e){
		var self = this;
		var rand = Math.random().toString().substr(2);
		$('body').prepend('<div id="tooltip_'+rand+'" class="trans_dark tooltip_left" style="top: '+(e.pageY)+'px; left: '+(e.pageX - 215)+'px;"><div class="head round_topleft"></div><div class="head_img"></div><div class="body round_bottom"></div></div>');
		
		$('#tooltip_'+rand+' > div.body').html($(self).attr('alt'));
		$('#tooltip_'+rand).fadeIn(300);
	});


	/* hide tooltip */
	$('ul#fav_widget_favmenu > li > a > img').mouseout(function(e){
        $('.tooltip_left').fadeOut(300, function() {
			$(this).remove();
		});
    });


    /*
     * Save
     */
    $('a.ajaxFavSave').live('click', function(event){  
        dialog($(this), 600, 390);
        return false;
    });


    /*
     * Load
     */
    $('a.ajaxFavLoad').live('click', function(event){   
        dialog($(this), 600, 300);
        return false;
    });


    /*
     * Clear
     */
    $('a.ajaxFavClear').live('click', function(event){
        dialog($(this), 380, 130);
        $('input.cancelBtn').live('click', dialogBlur);
        return false;
    });


    /*
     * Send
     */
    $('a.ajaxFavSend').live('click', function(event){ 
        dialog($(this), 600, 390);
        $('input.cancelBtn').live('click', dialogBlur);
        return false;
    });
	
    
    /*
     * Import Eport
     */
    $('a.ajaxFavImpExp').live('click', function(event){ 
        dialog($(this), 600, 500);
        return false;
    });

});
