var JQhomeObj;

if (typeof(DEBUG) == 'undefined') {
	DEBUG = false;
	if (document.location.search != null && document.location.search.length>1) {
		(function(){
			var s = document.location.search;
			if (s.match(/^\?/)) {
				s = s.substring(1);
			}
			var strParams = s.split('&');
			var params = {};
			var i = 0;
			for (i in strParams) {
				var name = strParams[i];
				var value = true;
				var pos = name.indexOf('=');
				if (pos>0) {
					value = name.substring(pos+1);
					name = name.substring(0, pos);
				}
				params[name] = value;
			}
			if (params.debug === true || params.debug == 'true' || params.debug == 'debug') {
				DEBUG = true;
			}
		})();
	}
}
if (typeof(debug) == 'undefined') {
	function debug(s) {
		if (DEBUG) {alert(s);}
	}
}

HomePack = function()
{
	var defaultCookie = {};
	var pageCookie;
	var initPageCookie;
	var arraySortable;
	var maxNumberCSS;
	var newCookie;
	var colorPage;
	var colorPageRandom;

	this.pageCookie = '';
	this.initPageCookie = null;
	this.newCookie="";
	this.ELEMENT_SORTABLE = ".ui-sortable";
	this.PATH_HTML_BLOCK = "/dl/portale/html/";
	this.PATH_HTML_BLOCK_SERVIZI = "/dl/portale/html/servizi/";
	this.PATH_HTML_BLOCK_PALINSESTI = "/dl/portale/html/palinsesti/";
	this.arraySortable = ["#A","#B","#C","#D","#E"];
	this.maxNumberCSS = 17;
	this.colorPage = 1;
	this.colorPageRandom = false;
}

HomePack.prototype =
{
	__blockQueue: [],
	__blockQueueIndex: 0,
	__blocksEnqueuing : false,
	__blocksLoading : 0,
	__blockLoadComplete: function() {
		if (!JQhomeObj.__blocksEnqueuing) {
			JQhomeObj.__clickAccordion();
			JQhomeObj.__toggleContent();
			JQhomeObj.__newsAddRemove();
			JQhomeObj.__lanciCarousel();
			//if (!DEBUG) JQhomeObj.__customiseHomepage();

			JQhomeObj.applyPngFix();
			JQhomeObj.setPageCookie(JQhomeObj.__getColumnsCookie());
		}
	},
	__loadNextBlock: function(o) {
		if (JQhomeObj.__blockQueue.length <= JQhomeObj.__blockQueueIndex) {
			JQhomeObj.__blockLoadComplete();
			return false;
		}
		var o = JQhomeObj.__blockQueue[JQhomeObj.__blockQueueIndex];
		JQhomeObj.__blockQueueIndex++;
		var s = o.success;
		o.success = (function(){
			var f = s;
			return function(html){
				JQhomeObj.__blocksLoading -= 1;
				f.call(JQhomeObj, html);
				JQhomeObj.__loadNextBlock();
			}
		})();
		JQhomeObj.__blocksLoading++;
		//setTimeout( (function(){var u = o.url; return function(){throw(u)};})(), 10);
		$.ajax(o);
	},
	__enqueueBlock: function(options) {
		JQhomeObj.__blockQueue[JQhomeObj.__blockQueue.length] = options;
	},
	__renderingHomePage : function()
	{
		//alert('__renderingHomePage');
		debug('JQhomeObj.__renderingHomePage starting...');
		var columns = $.evalJSON(JQhomeObj.pageCookie);
		JQhomeObj.__blocksEnqueuing = true;
		for (j in columns) {
			var type= columns[j].type, id = j, weburl = columns[j].weburl, col = columns[j].col, val = columns[j].view, state = columns[j].state, pos = columns[j].p;
			var trovato = false;
			$(":checkbox").each(function() {
				if($(this).attr("value") == j)
					trovato = true;
			});
			if(trovato) {
				// JQhomeObj.__blocksLoading++;
				// alert(weburl + "#########" + JQhomeObj.PATH_HTML_BLOCK+id+ ".html");
				JQhomeObj.__enqueueBlock({
				  async :true,
				  url: weburl,
				  success: (function(){
						var fCol = col;
						var fId = id;
						var fVal = val;
						var fState = state;
						var fType = type;
						var fPos = pos;
						var fWebUrl = weburl;
					  return function(html){
						var n = null;
						// alert(html);
						$(">div.groupItem", $(fCol)).each(function() {
							if ($(this).data('position')<fPos) {
								n = $(this);
							}
						});
						if (n == null) {
							// alert(fPos + ' va per primo');
							$(fCol).prepend(html);
						} else {
							// alert(fPos +' va dopo '+n.data('position'));
							n.after(html);
						}
						// $(fCol).append(html);
						$('#'+fId).data('position', fPos);
						if(fState == "-") {
							$("#"+fId+" div.itemContent").css('display','none');
							$("#"+fId+" div.itemHeader").toggleClass("hpCollapsed");
						}
						switch(fType) {
							case 2 :
								JQhomeObj.__setAccordion(fId,fVal ? fVal : 0 );
								break;
							case 3:
								// PALINSESTI
								JQhomeObj.__setPalinsesti(fId,fVal ? fVal : 0 );
								break;
							case 4:
								// SERVIZI
								JQhomeObj.__setServizi(fId,fVal ? fVal : 0 );
								break;
							default:
								JQhomeObj.__setVisibility(fId,fVal ? fVal : 3 );
							break;
						}
						// JQhomeObj.__blockLoadComplete();
					  };
					 })()
				});
			}
		}
		// debug('__renderingHomePage: '+JQhomeObj.__blockQueue.length);
		JQhomeObj.__blocksEnqueuing = false;
		JQhomeObj.__loadNextBlock();
		// if (JQhomeObj.__blocksLoading == 0) {
		//	JQhomeObj.__blockLoadComplete();
		// }
	},

	__getColumnsCookie : function() {
		var jsonForCookie = {};

		var j = 0,arrayLen = JQhomeObj.arraySortable.length, indice = 0;
		var columns = $.evalJSON(JQhomeObj.pageCookie);
		for (; j < arrayLen; j++) {
			$(JQhomeObj.arraySortable[j]).children().each(function(){
				var block = "", state = "", type = 0, state = "",view=0, weburl="", 
				state = $(this).children('.itemContent').css('display') == 'none' ? "-" : "+";
				block = $(this).attr('id');
				switch(block) {
					default :
						var list = $(this).children('.itemContent').children('.item').children();
						var blocked = list.filter("[class!='blocked']");
						view = blocked.length;
						type = 1;
						break;
				}
				weburl = columns[block].weburl;
				jsonForCookie[block] = {weburl : weburl, state : state, type : type, view : view, col : JQhomeObj.arraySortable[j], p : indice++};
			});
		}
		return jsonForCookie;
    },

	__lanciCarousel : function(id)
	{
		$('.lanci>li,.lanci2>li').mouseover(function() {
			$(this).parents('.lanci,.lanci2').children().children("a").removeClass("hover");
			$(this).children("a").addClass("hover");
			var link = $(this).children("a").attr("href");
			if (!$(this).parents('.lanci,.lanci2').is('.none') && $(this).children("span").html() != null && $(this).children("span").html() != '') {
				$(this).parents('.lanci,.lanci2').prev().attr("style","background-image: url("+$(this).children("span").html()+");");
			}
			$(this).parents('.lanci,.lanci2').prev().children("a").attr("href",link);
		});
		$('.lanci>li').css('height', '41px');
	},

	__setServizi : function(el,val)
	{
		//alert('__setServizi');
		JQhomeObj.__getHtmlBox(el,$("#"+el+">DIV.itemContent>DIV.info"),$("UL.tabServizi>LI:eq("+val+")").attr("id"));
		$("#"+el+">DIV.itemContent>UL.tabServizi>LI>A:eq("+val+")").addClass("selected");
		$("UL.tabServizi>LI").click(function() {
			$(".tabServizi li a").removeClass("selected");
			$(this).children("a").addClass("selected");
			JQhomeObj.__getHtmlBox(el,$("#"+el+">DIV.itemContent>DIV.info"),$(this).attr("id"));
			JQhomeObj.setPageCookie(JQhomeObj.__getColumnsCookie());
		});
	},
	__getHtmlBox : function(elBox,elID,val)
	{
		//alert('__getHtmlBox');
		var urlHTML = "";

		$.ajax({
			  async :false,
			  url: urlHTML,
			  success: function(html){
				elID.html(html);
				JQhomeObj.applyPngFix();
			  }
		});
	},
	__setAccordion : function(el,val)
	{
		//alert('__setAccordion');
		$("#"+el+">DIV.itemContent>UL.drawers>LI.drawer>div.drawer-container:not(:eq("+val+"))").slideUp("slow");
		$("#"+el+">DIV.itemContent>UL.drawers>LI.drawer>H2:eq("+val+")").addClass("open");
	},
	__clickAccordion : function()
	{
		//alert('__clickAccordion');
		$("H2.drawer-handle").click(function() {
			if ($(this).next().css('display') == 'none') {
				$(this).parents(".drawers").children(".drawer").children("h2").removeClass("open").next().slideUp("slow");
				$(this).addClass('open').next().slideDown("slow");
				JQhomeObj.setPageCookie(JQhomeObj.__getColumnsCookie());
			}
		});
	},
	/******************************************* PALINSESTI inizio******************************************************************************/
	__setPalinsesti : function(el,val)
	{
		//Per ora la lascio...ma forse sarà da cancellare dato che è tutto in flash...
	},
	/******************************************* PALINSESTI fine ******************************************************************************/
	__newsAddRemove : function(id)
	{
		$('a.add, a.remove').click(function() {
			var link = $(this);

			var list = $(this).parents('.itemContent').children('.item').children();
			var blocked = list.filter(".blocked");

			if(link.is('.add')){
	            if (blocked.length) {
	                $(blocked[0]).removeClass("blocked");
	                //this.data.get("a.remove").css("opacity", "1").attr("href", "#");
	            }
			}

			if(link.is('.remove')){
	            if (blocked.length <= list.length - 1) {
	                //this.data.get("a.add").css("opacity", "1").attr("href", "#");
	                $(list[list.length - blocked.length - 1]).addClass("blocked");
	            }
			}
			JQhomeObj.setPageCookie(JQhomeObj.__getColumnsCookie());
		});
	},
	__setVisibility : function(el,val){
		$("#"+el+">DIV.itemContent>UL.item>LI:gt("+(val-1)+")").addClass("blocked");
	},
	__toggleContent : function(e)
	{
		$("a.toggle").click(function() {
			var targetContent = $(this).parents('.itemHeader').next();
			targetContent.slideToggle("slow",function () {
				$(this).prev().toggleClass("hpCollapsed");
				JQhomeObj.setPageCookie(JQhomeObj.__getColumnsCookie());
			});
			$(this).parents('.FootHeader').next().slideToggle("slow",function () {
				$(this).prev().toggleClass("hpCollapsed");
			});
		});
	},

	__customiseHomepage : function(e)
	{
		//alert('__customiseHomepage');
		/******************** INIZIO  SETTAGGIO CSS *******************/
		$("body").attr("class","hp"+JQhomeObj.colorPage);
		/******************** FINE SETTAGGIO CSS ************************/

		/******************** INIZIO  SETTAGGIO INPUT BOX *******************/
        $("div.feedSelection input").each(function() {
            if(JQhomeObj.pageCookie.search($(this).val()) > -1) {
                $(this).attr("checked", true);
                $(this).parent().addClass("enabled")
            }
            $(this).click(function() {
                $(this).parent().toggleClass("enabled")
            });
        });
		/******************** FINE   SETTAGGIO INPUT BOX ************************/
		$("#reset").click(function() {
			utils.cookie.remove("np_"+PAGE,'/',HOST);
			utils.cookie.remove("hpColor_"+PAGE,'/',HOST);
			utils.cookie.remove("css_"+PAGE,'/',HOST);
			window.location.reload();
		});
		/******************** INIZIO   SETTAGGIO COLOR ************************/
		if(JQhomeObj.colorPageRandom)
			$("UL.list_Color a:eq(0)").addClass("enabled");

		$("UL.list_Color a:eq("+JQhomeObj.colorPage+")").addClass("enabled");

		$("UL.list_Color a").click(function() {
			var index = $("UL.list_Color a").index(this);
			$("UL.list_Color a").removeClass("enabled");
			$("UL.list_Color a:eq("+index+")").addClass("enabled");
			return false;
		});
		/******************** FINE   SETTAGGIO COLOR ************************/
		$("#submit").click(function() {
			//JQhomeObj.newCookie = JQhomeObj.pageCookie;
			var block = "", state = "", type = 0, state = "", block = "",view=0, weburl="";
			var  jsonForCookie = $.evalJSON(JQhomeObj.pageCookie);
			var initCookieColumn = $.evalJSON(JQhomeObj.initPageCookie);
			//alert('JQhomeObj.initPageCookie' + JQhomeObj.initPageCookie);
			$(":checkbox").each(function() {
				block = $(this).attr("value");
				if($(this).parent().is('.enabled')) {
					if(typeof(jsonForCookie[block]) == 'undefined') {
						switch(block) {
							default :
								view = 3;
								type = 1;
								break;
						}
						state = "+";
						weburl = initCookieColumn[block].weburl;
						col = initCookieColumn[block].col;
						jsonForCookie[block] = {weburl: weburl, state: state, type: type, view: view, col : col, p : -1};
					}
				} else {
					delete jsonForCookie[block];
				}

			});
			var tmpArr = [];
			var tmpArr2 = [];
			for (i in jsonForCookie) {
				if (jsonForCookie[i].p != -1) {
					tmpArr[jsonForCookie[i].p] = {k: i, v: jsonForCookie[i]};
				} else {
					tmpArr2.push({k: i, v: jsonForCookie[i]});
				}
			}
			jsonForCookie = {};
			for (i in tmpArr2) {
				jsonForCookie[tmpArr2[i].k] = tmpArr2[i].v;
				tmpArr2[i].v.p = parseInt(i);
			}
			for (i in tmpArr) {
				jsonForCookie[tmpArr[i].k] = tmpArr[i].v;
				tmpArr[i].v.p = parseInt(i) + parseInt(tmpArr2.length);
			}
			JQhomeObj.setPageCookie(jsonForCookie);
			/*********** Colore Home *****************************/
			var color = $("UL.list_Color a").index($("UL.list_Color a").filter(".enabled"));
			utils.cookie.set("hpColor_"+PAGE,color,10,'/',HOST,'');
			window.location.reload();
			//JQhomeObj.initHome();
		});
	},
	initHome : function()
	{
		//alert('initHome');
		JQhomeObj = this;
		JQhomeObj.setPageCookie();
		//alert(JQhomeObj.initPageCookie);
		if (JQhomeObj.initPageCookie == null)
			JQhomeObj.setInitPageCookie();
		JQhomeObj.setColorPage();
		//if (DEBUG) JQhomeObj.__customiseHomepage();
		JQhomeObj.__customiseHomepage();

		$(JQhomeObj.ELEMENT_SORTABLE).sortable({
			items: '> .groupItem',
			handle: 'div.itemHeader',
			connectWith: JQhomeObj.arraySortable,
			tolerance: 'guess',
			cursor: 'move',
			placeholder:'placeholder',
			appendTo: 'body',
			delay: 100,
            forcePlaceholderSize: true,
            revert: 300,
			helper: function(e, el) {
					var l = $('#A').add('#D').add('#E');
					var maxBot = 0;
					l.each(function(){
						var b = $(this).position().top+$(this).height();
						maxBot=(b>maxBot)?b:maxBot;
					});
					l.each(function(){
						var h = (maxBot - $(this).position().top);
						//disattivato: altrimenti non si riesce a rimettere il blocco nella colonna di partenza.
						//if (h <= $(this).height()) return true;
						var id = $(this).attr('id');
						$(this).attr('style', 'height: '+h+'px !important');
					});
					$(JQhomeObj.ELEMENT_SORTABLE).sortable('refreshPositions');
				return el.clone();
			},
			start: function(e,ui) {
				/*$(".groupItem div.itemContent").css('display','none');
				$(".groupItem div.itemHeader").addClass("hpCollapsed");
				$('html,body').animate( {scrollTop: $( '#E' ).offset().top});*/
				ui.helper.css("width", ui.item.width());
			},
			stop : function() {
				/*var columns = $.evalJSON(JQhomeObj.pageCookie);
				for (j in columns) {
					if(columns[j].state == "+") {
						$("#"+j+" div.itemContent").css('display','block');
						$("#"+j+" div.itemHeader").toggleClass("hpCollapsed");
					}
				}*/

				JQhomeObj.setPageCookie(JQhomeObj.__getColumnsCookie());
				$('#A').add('#D').add('#E').attr('style', 'height: auto !important; height: 200px;');
			}
		});

		JQhomeObj.__renderingHomePage();
		//var timerIdHome = setInterval('JQhomeObj.setNielsen()',60000*15);
	},
	applyPngFix : function()
	{
		var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1])

		if ((version >= 5.5) && (version < 7) && (document.body.filters))
		{
		   for(var i=0; i<document.images.length; i++)
		   {
		      var img = document.images[i]
		      var imgName = img.src.toUpperCase()
		      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
		      {
		         var imgID = (img.id) ? "id='" + img.id + "' " : ""
		         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		         var imgStyle = "display:inline-block;" + img.style.cssText
		         if (img.align == "left") imgStyle = "float:left;" + imgStyle
		         if (img.align == "right") imgStyle = "float:right;" + imgStyle
		         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
		         var strNewHTML = "<span " + imgID + imgClass + imgTitle
		         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
		         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
		         img.outerHTML = strNewHTML
		         i = i-1
		      }
		   }
		}
	},

	/** SET  e  GET  *****************************************************************************************************/
	setPageCookie : function(cookieJSON)
	{
		if (!utils.cookie.get("np_"+PAGE)) {
			this.pageCookie = $.toJSON(JQhomeObj.defaultCookie);
			utils.cookie.set("np_"+PAGE,$.base64Encode(this.pageCookie),10,'/',HOST,'');
		} else {
			if(cookieJSON == undefined){
				var tmpString = utils.cookie.get("np_"+PAGE);
				var validBase64 = false;
				try {
					$.evalJSON($.base64Decode(tmpString));
					validBase64 = true;
				} catch(e) {
					validBase64 = false;
				}
				if (validBase64) {
					tmpString = $.base64Decode(tmpString);
				}
				this.pageCookie = tmpString;
			} else {
					this.pageCookie = $.toJSON(cookieJSON);
					utils.cookie.set("np_"+PAGE,$.base64Encode(this.pageCookie),10,'/',HOST,'');
			}
		}
	},
	setInitPageCookie : function(cookieJSON)
	{
			this.initPageCookie = $.toJSON(JQhomeObj.defaultCookie);
			
	},
	setColorPage : function()
	{
		if (utils.cookie.get("hpColor_"+PAGE)) {
			if (utils.cookie.get("hpColor_"+PAGE) != "0") {
				this.colorPage = utils.cookie.get("hpColor_"+PAGE);
			} else {
				this.colorPage = Math.ceil(JQhomeObj.maxNumberCSS*Math.random());
				this.colorPageRandom = true;
			}
		}
	},

	getColorPage : function()
	{
		var arrayColor = new Array("#8aa100","#2375c8","#4b362b","#204541","#5c6d51","#718b8c","#47a5ba","#14b4b4","#657287","#405273","#614d8a","#683f57","#934b85","#c7377f","#ab5b32","#e18d38","#d9b74c","#a6a73b");
		return arrayColor[JQhomeObj.colorPage];
	},
	
	getColorArray : function()
	{
		var arrayColor = new Array("8aa100","2375c8","4b362b","204541","5c6d51","718b8c","47a5ba","14b4b4","657287","405273","614d8a","683f57","934b85","c7377f","ab5b32","e18d38","d9b74c","a6a73b");
		return arrayColor;
	},

	createFlash : function(variabili)
	{
		if ($.browser.msie) {
		
			var flash = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+variabili.width+'" height="'+variabili.height+'" id="'+variabili.id+'" align="middle">'
						+'<param name="allowScriptAccess" value="sameDomain" />'
						+'<param name="allowFullScreen" value="true" />'
						+'<param name="movie" value="'+variabili.src+'.swf" />'
						+'<param name="quality" value="high" />'
						+'<param name="wmode" value="transparent" />'
						+'<param name="flashvars" value="'+variabili.flashvars+'" />'
						+'</object>';
			//alert(flash);
		} else {
			var flash = '<embed src="'+variabili.src+'.swf" quality="high" wmode="transparent" width="'+variabili.width+'" height="'+variabili.height+'" name="'+variabili.name+'" align="middle" allowScriptAccess="sameDomain" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+variabili.flashvars+'" />';
			//alert(flash);
		}

		$(variabili.elHtml).html(flash);
	}

	/****************************************************************************************************/
}
