(function($) {
    $.seezam = {};    
})(jQuery);

$(document).ready(function(){
    /* ADD SPECIFICED CLASS NAME FOR FORM'S ELEMENTs */
    $('input[type=text], input[type=password], textarea').addClass('input-text').hover(function(){$(this).addClass('input-text-hover')},function(){$(this).removeClass('input-text-hover')});
    $('input[type=submit], input[type=button], input[type=reset]').addClass('input-button');
    $('input[type=radio]').addClass('input-radio').hover(function(){$(this).addClass('input-radio-hover')},function(){$(this).removeClass('input-radio-hover')});
    $('input[type=checkbox]').addClass('input-checkbox').hover(function(){$(this).addClass('input-checkbox-hover')},function(){$(this).removeClass('input-checkbox-hover')});
    $('select').addClass('input-select').hover(function(){$(this).addClass('input-select-hover')},function(){$(this).removeClass('input-select-hover')});    
    /* SEARCH FIELD */
    $('input[name=searchField]').hover(function(){
        if($(this).attr('title') == '') {
            $(this).attr('title', $(this).val());
        }
        if($(this).val() == $(this).attr('title')) {
            $(this).val('');
        }
    }, function(){
        if($(this).val()=='') {
            $(this).val($(this).attr('title'));
        }
    });
    /* LOGIN TABS */
    $('div#loginTabContent > div').hide();
    $('ul#loginTab').find('a').each(function(){        
        if($(this).hasClass('current')) {
            $('div' + $(this).attr('href') + '_mode').show();
            setLoginType($(this).attr('href'));
        }
        $(this).click(function(e){
            e.preventDefault();
            $(this).parent().parent().find('a').each(function(){
               $(this).removeClass('current'); 
            });
            $(this).addClass('current');
            $('div#loginTabContent > div').hide();
            $('div' + $(this).attr('href') + '_mode').show();
            setLoginType($(this).attr('href'));
        });
    });  
    /* MY SEEZAM - CATEGORIES */        
    $.fn.seezam_draggable = function(){
        return this.each(function(){
            var c = $(this);
            c.draggable({
            	containment: "#contentBox", 
        		helper: 'clone',
            	sectionId: 1,
                opacity: 0.5,
                revert: 'invalid',
                scope: 'categories',
                start: function(event, ui) {
                    c.attr({'x':c.offset().top,'y':c.offset().left});
                }
            });
            $(this).find('a.mysz-cat-expander').click(function(e){
               e.preventDefault(); 
               if(c.hasClass('mysz-cat-open')) {
                   c.find('div.mysz-cat-body').slideUp(100);
                   c.removeClass('mysz-cat-open');
               } else {
                   c.parent().find('div.mysz-cat').each(function(){
                       $(this).removeClass('mysz-cat-open');
                       $(this).find('div.mysz-cat-body').slideUp(100);
                   });
                   c.find('div.mysz-cat-body').slideDown(100);               
                   c.addClass('mysz-cat-open');
               };
            });
            $(this).find('a.mysz-cat-delete').click(function(e){
            	var numOfItem = ($(this).attr("rel"));
            	if(numOfItem != "" && parseInt(numOfItem) > 0){
            		var errormsg = $("#myseezam_error_delete_category_not_empty").html();
            		var buttons = {};
            		buttons[messages.button_yes] = function() {
                        $(this).dialog('close');
                    };
                    $('<div title="' + messages.link_delete_warning + '"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>'+errormsg+'</p></div>').dialog({
                         bgiframe: true,
                         resizable: false,
                         height:200,
                         width:300,
                         zIndex: 1151,
 	                     modal: true,
                         overlay: {
                             backgroundColor: '#000',
                             opacity: 0.5
                         },
                         buttons: buttons
                    });
                    $('.ui-dialog-buttonpane button:contains(' + messages.button_yes+ ')').removeClass('ui-state-default').removeClass('ui-corner-all').addClass("button_green");
                    return;
            	}else{
            		var buttons = {};
            		buttons[messages.button_yes] = function() {
            			e.preventDefault();
                        $.post(ContextPath + '/deletecategory.htm', {'categoryId': c.attr('id').split('-')[2], 'sectionId': c.attr('section')}, function(data, textStatus){
                            if(textStatus == 'success') {
                                c.remove();
                            }           
                        }, 'text');
                        $(this).dialog('close');
                    };
            		buttons[messages.button_cancel] = function() {
            			$(this).dialog('close');
            		};
	                $('<div title="' + messages.link_delete_confirmation + '"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + messages.link_remove_warning_category + '</p></div>').dialog({
	                    bgiframe: true,
	                    resizable: false,
	                    width:450,
	                    height:150,
	                    modal: true,
	                    zIndex: 1151,
	                    overlay: {
	                        backgroundColor: '#000',
	                        opacity: 0.5
	                    },
	                    buttons: buttons
	                });
	                $('.ui-dialog-buttonpane button:contains(' + messages.button_yes+ ')').removeClass('ui-state-default').removeClass('ui-corner-all').addClass("button_green");
	                $('.ui-dialog-buttonpane button:contains(' + messages.button_cancel+ ')').removeClass('ui-state-default').removeClass('ui-corner-all').addClass("button_red");
                }
            });
        });
    };
    function sortCategory(section) {
	    var cats = new Array(); 
	    $('div#section-'+section+' div.mysz-cat').each(function(){
	    	e = $(this);
	    	title = e.find('.mysz-cat-title > a').text();
	    	cats[title] = e.clone();
	    	e.remove();
	    });
	    cats = cats.sort();
	    var keys = new Array();
	    for (var i in cats) {	    	
	    	keys.push(i);
	    }
	    keys.sort();
	    for (var i = 0; i < keys.length; i++) {
	    	$('div#section-'+section).append(cats[keys[i]]);
	    }
    }
    sortCategory('public');
    sortCategory('confidential');
    sortCategory('private');
    $('div.mysz-cat').seezam_draggable();
    $('.seezam-droppable').each(function(){
        $(this).droppable({
        accept: 'div.mysz-cat',
        scope: 'categories',
        hoverClass: 'seezam-droppable-hover',
        drop: function(event, ui) {
            var o = ui.draggable; //old object
            var target = 0;            
            switch($(event.target).attr('id')) {
                case 'section-public':
                    target=1;
                    break;
                case 'section-confidential':
                    target=2;
                    break;
                case 'section-private':
                    target=3;
                    break;
            }
            if(target == o.attr('section')) {
                moveCategoryRevert(o, event);
                return false;
            }
            if(target == 1) {
                var answer;
                var buttons = {};
                buttons[messages.button_move_yes] = function() {
                    moveCategoryAjaxCall(o, 1, event);
                    o.attr('section',target);
                    $(this).dialog('close');
                };
                buttons[messages.button_cancel] = function() {
                    moveCategoryRevert(o);
                    $(this).dialog('close');
                };
                $('<div title="' + messages.link_move_confirmation + '"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + messages.link_move_warning + '</p></div>').dialog({
                	closeOnEscape: false,
                	bgiframe: true,
                    resizable: false,
                    height:200,
                    width:400,
                    zIndex: 1151,
                    modal: true,
                    overlay: {
                        backgroundColor: '#000',
                        opacity: 0.5
                    },
                    buttons: buttons
                });
                $('.ui-dialog-buttonpane button:contains(' + messages.button_cancel+ ')').removeClass('ui-state-default').removeClass('ui-corner-all').addClass("button_red");
                $('.ui-dialog-buttonpane button:contains(' + messages.button_move_yes+ ')').removeClass('ui-state-default').removeClass('ui-corner-all').addClass("button_green");
                $(".ui-dialog-titlebar-close").hide();
    	    } else {
                o.attr('section',target);
                moveCategoryAjaxCall(o, target, event);
            }
        }
    })
    });
    function moveCategoryAjaxCall(o, target, event) {
        var id = o.attr('id').split('-')[2]; 
        $.post(ContextPath+'/movecategory.htm', {'categoryId':id,'sectionId':target}, function(data, textStatus){
            if((textStatus == 'success') && (data == 'OK')) {
                moveCategoryDropped(o, event);
                // redirect to the share contact page
                if(target == 2){ // only for case "confidential"
                	document.location.href = ContextPath+'/movecategorysharecontact.htm?categoryId='+id;
                }
            } else {
                moveCategoryRevert(o);
            }
        }, 'text');
    }
    function moveCategoryDropped(o, event) {
    	$(event.target).find('.empty_section_message').hide();
        var n = o.clone(false); // new object
        n.removeAttr('style').css('opacity', '0').appendTo($(event.target).find('.seezam-droppable-container'));
        var x = o.offset().top-n.offset().top;
        var y = o.offset().left-n.offset().left;
        o.animate({                
            top: ((x<0)?'+=':'-=')+Math.abs(x),
            left: ((y<0)?'+=':'-=')+Math.abs(y),
            opacity: 0
        }, '800', function(){
            o.remove();
            n.animate({
                'opacity': 1
            }, 100, function(){
                n.seezam_draggable();
            });
        });
    }
    function moveCategoryRevert(o){
        var x = o.offset().top-o.attr('x');
        var y = o.offset().left-o.attr('y');
        o.animate({                
            top: ((x<0)?'+=':'-=')+Math.abs(x),
            left: ((y<0)?'+=':'-=')+Math.abs(y),
            opacity: 1
        }, 'slow');
    }
    /* DELELE ITEM */
    updateContactList();
    
    /* NEW ITEM EXPANDER */
    $('#newitem-expander, #edititem-expander').click(function(){
       var $this = $(this);
       if($this.hasClass('expand_top')) {           
           $('div.new_item').slideUp('slow',function(){
               $this.removeClass('expand_top').addClass('expand_bot');
           });
       } else {
           $('div.new_item').slideDown('slow',function(){
               $this.removeClass('expand_bot').addClass('expand_top');
           });
       }
    });
    /* CONTACT DETAIL EXPANDER */
    $('#viewcontact > .expander').click(function(){    	
       var container = $(this).parent();
       if($(this).hasClass('expander-right')) {
           $(this).removeClass('expander-right');           
       } else {
           $(this).addClass('expander-right');
       }           
       container.children().not('.expander').each(function(){
           if($(this).hasClass('wide'))
               $(this).removeClass('wide').addClass('narrow');
           else 
               $(this).removeClass('narrow').addClass('wide');
       });
       fixHeight();
       $('div.box_title_blue').truncate();
    });
    $('#viewcontact').find('.heading').click(function(){
        if($(this).parent().hasClass('narrow'))
            $('#viewcontact > .expander').click(); 
    });
    
    $.fn.truncate = function() {
    	$('<span id="jquery-truncate-tmp" style="display: none;"></span>').appendTo('body');
    	$('#jquery-truncate-tmp').text(' &hellip;');
    	var hellip = $('#jquery-truncate-tmp').width();
	    this.each(function(){	    	
	    	var width = $(this).width()-parseFloat($(this).css('padding-left'))-parseFloat($(this).css('padding-right'))-5-hellip;
	    	if(width > 0) {
	    		
		    	if($(this).attr('jquery-truncate') == null) {
		    		$(this).attr('jquery-truncate', $(this).text());
		    	}
	            $('#jquery-truncate-tmp').text($(this).attr('jquery-truncate'));
			    while($('#jquery-truncate-tmp').width() > width) {
				    $('#jquery-truncate-tmp').html($('#jquery-truncate-tmp').text().substr(0, ($('#jquery-truncate-tmp').text().lastIndexOf(String.fromCharCode(32)))));
			    }
			    $(this).html($('#jquery-truncate-tmp').text() + (($('#jquery-truncate-tmp').text().length != $(this).text().length)?' &hellip;':''));			    	    		
	    	}    		    	
	    });	    
	    $('#jquery-truncate-tmp').remove();
	    return $(this);
    };
    /* OPEN LINKS IN NEW TAB*/
    $('.newtab').find('a').attr('target', '_blank');
});

function updateContactList() {
	$('div.contact-name').hover(
       function(){
           $(this).addClass('contact-name-hover');
       },
       function(){           
           $(this).removeClass('contact-name-hover');
       }
    );
}

