var profileClass = {

    tplURL : "/global/contents/profile/profile.js",
    tplReference : ".profile",
    datasource: "profile_tpl",
    galleries :[{"galleryinfo":{
    	"title":"Profile Gallery",
    	"privilege":null,
    	"rating":"0",
    	"viewcount":"0",
    	"price":null,
    	"mainitemid":"none",
    	"sortnumber":"0",
    	"type":"picture",
    "galleryitems":[{
    	"id":"none",
    	"filename":"none.jpg",
    	"category":null,
    	"type":"picture"}]}
    }],
	init: function(_accountId){
		
		// setting variabili;
		this.scrollInt= 0;
		this.menu;
    	this.imgGallery;
    	this.pop = [];
    	this.newMenuPos = 0;
    	this.menucolumnH;
    	$("#profileContainer").css('opacity', 0);
    	if ($.browser.msie) $("#profileContainer").css('filter', 'Alpha(opacity=0)');
    	var self = this;
    	$.post('/profile/'+_accountId+'/json',function(data){
    		self.account = $.extend(self.account, data.account);
    		if(data.galleries.length != 0){
    			self.galleries = data.galleries;
    		}else{
    			self.galleries = [{"galleryinfo":{
    		    	"title":"Profile Gallery",
    		    	"privilege":null,
    		    	"rating":"0",
    		    	"viewcount":"0",
    		    	"price":null,
    		    	"mainitemid":"none",
    		    	"sortnumber":"0",
    		    	"type":"picture",
    		    "galleryitems":[{
    		    	"id":"none",
    		    	"filename":"none.jpg",
    		    	"category":null,
    		    	"type":"picture"}]}
    		    }];
    		}
        	self.profile = $.extend(self.profile, data.profile);
        	
	        $("#profile_galleries, .default").css({
	            display: 'block',
	            opacity: 1
	        });
	        $(this.tplReference).show();
	    	
	    	// set Icon menu
	    	profileClass.setIconMenu(self.menu,self.galleries[0].galleryinfo.mainitemid);
	    	
	    	// check Menu Overflow
	        profileClass.chkMenuColumnOverflow();
	    	
	    	
	        $("#profile_menu_column_content").scrollTop(this.newMenuPos);
	        
	        //carica immagine del profilo
	        profileClass.loadImage(self.galleries[0].galleryinfo.mainitemid,self.galleries,self.profile);
	    	
	    	// carcia i dati account
	    	profileClass.loadContentaccount(self.profile);
	    	
	    	// set scroll
	    	profileClass.setScroll();
	    	
	    	// set drawer
	    	profileClass.setDrawer();
	    	
	        // carica la galleria
	    	profileClass.loadGallery(self.galleries);
	    	    
    	});
	},
	loadContentaccount : function(profile){
		
		$(this.tplReference+ ' .corn .name').append(profile.nickname);
		
		if(profile.sex!=1){
			$(this.tplReference+ " #info_minimal #user_type").removeClass('member-uomo').addClass('member-donna');
		}
		
		if(profile.birthday!=undefined){
			$(this.tplReference+ ' .corn .age').append($.age(profile.birthday));
		}

		$(this.tplReference+ ' .corn .hobbies').append(profile.hobbies);
		$(this.tplReference+ ' .corn .introduction').append(profile.introduction);
		
		
		$.fn.geonames("getLocationFromPoint",{lat:profile.lat,lon:profile.lon},function(result){
			//$.trace(result);
			$(profileClass.tplReference+ ' .corn .city').append(result.name+", "+result.adminName1);
			$(profileClass.tplReference+ ' .corn .country').append(result.countryName);
		});   
	},
	loadGallery:function(galleries){
		for (i in galleries){
            var gal = galleries[i];
            var gallery = "<div id='"+galleries[i].galleryinfo.id+"' class='gallery'></div>";
            $(this.tplReference+ ' .corn #profile_galleries').append(gallery);
            $(this.tplReference+ ' .corn #'+galleries[i].galleryinfo.id).galleryMenu(gal);
        };
        $(this.tplReference+ ' .gallery .item').click(function (e){
        	var loadItemId="carica itemid";
        	profileClass.loadImage($(e.target).attr('id'),galleries,loadItemId);
        });
        
        $("#profile_menu_column_content").mousewheel(function(e, delta){
            profileClass.scrollCont(-delta/2);
        });
	},
	loadImage: function (itemId, galleries,loadItemId,profile)
    {
		var src="";
		if(loadItemId!= undefined){
			src ="http://"+domain+"/item/get/picture/big/"+itemId;
		}else{
			src ="http://"+domain+"/profile/"+profile.id+"/picture/big";
		};

        $.cacheImage(src,{
        	
            load : function (e) {
                profileClass.loadContent("<img class='loader' gal='"+galleries[0].galleryinfo.id+"' src='"+src+"' id='"+itemId+"' alt='' title='"+galleries[0].galleryinfo.title+"' />",galleries);
            },
            error: function (e) {
            	$.trace("error load image", e);
            },
            abort: function (e) {
            	$.trace("abort load image", e);
            }
        }); 

    },
    loadContent: function (cont,galleries)
    {
    	
    	if (!$.browser.msie)  $(this.tplReference+' #profile_content_container').hide();
        
    	$(this.tplReference+' #profile_content_loader').show();
    	
        $(this.tplReference+' #profile_content_container').html('<div id="profile_content_loaded">'+cont+'</div>');
               
        //Sfoglia le immagini
        $(this.tplReference+' #profile_content_loaded').children().click(function(e){
            profileClass.nextImage(e,galleries);
        });
        var self=this;
        $(this.tplReference+' #profile_content_loaded').children().load(function(e)
        {
        	$('#profileContainer').css('opacity', 1);
        	if ($.browser.msie) $("#profileContainer").css('filter', 'Alpha(opacity=1)');
        	$(self.tplReference+' #profile_content_loader').hide();
            $(self.tplReference+' #profile_content_loaded').show();
            var imgProfileW = e.currentTarget.naturalWidth;
            var imgProfileH = e.currentTarget.naturalHeight;
            
            var profileContentW = $('.profile').width();
            var profileContentH = $('.profile').height();
            
            heightHF = $(".header").height() + $(".footer").height();
            if(heightHF==0){
            	heightHF = 100;
            }
            //console.log(e,imgProfileW, imgProfileH, profileContentW, profileContentH, heightHF, heightHF);
           	var data = imageRatio(imgProfileW, imgProfileH, profileContentW, profileContentH, heightHF, heightHF);
            var w = data.width;
            var h = data.height;
            if(h<=300){
            	w = 300*data.width/h;
            	h = 300;
            	
            }
            $(this).width(w);
            $(this).height(h);
            
            var offset = $('.profile #profile_content').css('padding-bottom');
            offset = parseInt(offset.substr(0,offset.length-2));
            
            $('.profile #profile_content').width(w);
            $('.profile #profile_content').height(h);
            $('.profile #profile_content').css('height', h+'px');
            $('.profile #profile_menu_column_content').height(h);
            
            if (!$.browser.msie) $(".profile #profile_content_container").animate({
                opacity:'toggle'
            },1000);

        	if($.browser.msie && parseInt($.browser.version) < 10 ){
                $(".profile #profile_menu_column_content").css({
                    'width': '165px',
                    'height': h+'px' // per ie
                });
            }
            $(".profile #profile_menu_column_content").scrollTop(0).fadeIn(50, function() {
                 profileClass.reposition();
            });

        });
    },
    nextImage: function (e,galleries){
        var galName = $(e.target).attr('gal');
        var imgName = $(e.target).attr('id');
        var nextImg = "";
        $.each(galleries,function(key, val){
        	galleryItems=galleries[key].galleryitems;

        	if(galleryItems.length == 1){
        		return
        	}
            $.each(galleryItems, function(index, value) {        	
                if(value.id == imgName){
                	next = index+1 < galleryItems.length ? index + 1 : 0;
                	nextImg = galleryItems[next].id;      
                }
            });
        });

        var loadItemId="carica itemid";
        profileClass.loadImage(nextImg,galleries,loadItemId);
    },
	setIconMenu : function(menu,itemId){
		var self = this;
		$(profileClass.tplReference+" #profile_menu").icoLinkMenu({
			menuItems:[ 
			{icoClass:'mipiace',
				 text:$.lng('global','like_to')
            },
            {icoClass:'amici_aggiungi',
                 text:$.lng('global','friend_to')
            },
            {icoClass:'preferiti_aggiungi',
                 text:$.lng('global','favorites')
            },
            {icoClass:'regali',
            	 text:$.lng('global','gift_to')
            },
            {icoClass:'caccia',
            	 text:$.lng('global','hunt_to')
            },
            {icoClass:'messaggi',
           	 	 text:$.lng('global','conversations')
            },
            {icoClass:'blocca',
            	 text:$.lng('global','ban_to')
            },
            {icoClass:'problema',
            	 text:$.lng('global','problem')
            }],
        highlight: 'background',
        itemColor : 'default',
        itemType: 'ico_text',
        direction: 'vertical'
        });
        $(this.tplReference+ " #winMenu").icoLinkMenu({
            menuItems:[{
                icoClass:'overlay',
                text:$.lng('global','overlay')
            },{
                icoClass:'chiudi',
                text:$.lng('global','close'),
                link:	 'javascript:profileClass.close();'
            }],
            highlight:'none',
            itemType:'ico',
            direction:'horizontal'
        });
       
        // Action 
        $(profileClass.tplReference+" #profile_menu").find('a').click(function(e){
        	stopPropagationFunction(e);
            var action = $(e.target).attr('id').split('a_')[1];
            interactionClass.interact(action, self.profile.id);
        });
        
        $(this.tplReference+ " .ico-link-menu-item").not('[href]').click(function(e){
            if($(e.target).attr('id')=="winMenu_chiudi"){
                $(".profile").hide();
                clearInterval (this.scrollInt);
                contentClass.closePreload();
                return(false);
            }
            if($(e.target).attr('id')=="winMenu_overlay"){
                var h=500;
                var w=700;
                var url="";
                pop[$('body').data('id')] = window.open(url, 'profile'+$('body').data('id'), 'height='+h+',width='+w+',scrollbars=0,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,copyhistory=0,left=50,top=50');
                pop[$('body').data('id')].focus();
                $('#winMenu_chiudi').click();
                return(false);
            }
            $(".profile").hide();
        });

	},
	setDrawer:function(){
		
		$(this.tplReference+" #drawer_info").drawer({
            title:"info",
            state:'open'
        });
		$(this.tplReference+" #drawer_galleries").drawer({
            title:"foto",
            state:'close'
        });
		
		profileClass.chkMenuColumnOverflow();
		profileClass.contColumnH();
        $(this.tplReference+" .drawer").resize( function(){
            profileClass.chkMenuColumnOverflow();
            profileClass.contColumnH();
        });
        
	},
	setScroll : function(){
		var self = this;
		// scroller ////////////////
        $("#profileScrollerBottom").mouseenter(function(){
        	self.scrollInt = setInterval("profileClass.scrollCont(1)", 50 );
        }).mouseleave(function(){
            clearInterval(self.scrollInt);
        });
        $("#profileScrollerTop").mouseenter(function(){
        	self.scrollInt = setInterval("profileClass.scrollCont(-1)", 50 );
        }).mouseleave(function(){
            clearInterval(self.scrollInt);
        });
        // end scroller ////////////////
        
	},
    scrollCont: function (step)
    {
    	this.newMenuPos = Math.max( Math.min( $("#profile_menu_column_content").scrollTop() + step*20 , this.menucolumnH ) , 0 );
        $("#profile_menu_column_content").scrollTop(this.newMenuPos);
        if( $("#profile_menu_column_content").scrollTop() == 0 || $("#profile_menu_column_content").scrollTop() == this.menucolumnH) {
            clearInterval(this.scrollInt);
        };
    },
    authContent: function (cont)
    {
        return $(cont).attr('filtered') == "false";
    },
    reposition: function()
    {
        $('.profile').css({
            top: '50%',
            'margin-top': - $('.profile').outerHeight()/2,
            left: '50%',
            'margin-left': - $('.profile').outerWidth()/2
        }).fadeIn(50);

        $('.loading').fadeOut(50, function() {
            startprofile = false;
        });
    },
    chkMenuColumnOverflow: function (){
        if( ( profileClass.contColumnH() ) > 0 ) $("#profile_menu_column .scroller").css({
            opacity:1
        }); else  $("#profile_menu_column .scroller").css({
            opacity:1
        });
    },
    contColumnH: function (){
        var contH = 0;
        var target = $("#profile_menu_column_content");
        target.children().each(function(index, domEle)
        {
            contH += $(domEle).outerHeight(true);
        });
        this.menucolumnH = contH - target.height();
        return contH - target.height();
    },
    galleryAccessDeny: function (gallery_type,gallery_id){
        switch (gallery_type){
            case "password":
                alert("qui apre un 'dialog' col campo password "+$('body').data('id'));
                break;

            case "amici":
                alert("Questa galleria è visibile solo dagli amici "+$('body').data('id'));
                break;

            case "pagamento":
                alert("Questa galleria costa 200p. Vuoi comperare l'accesso? "+$('body').data('id'));
                break;
        }
    },
    close:function(){
    	$("#profileContainer").empty();
    }
};

