var getById = function(el) {
	return document.getElementById(el);
}

var maf = {};

var laley = {
	
	flagSip : 1,
	
	actionPath: {
		favouriteAddFormMain: "/maf/app/favourites/addform",
		favouriteAddFormCreateFolder: "/maf/app/favourites/addform/createFolder",
		favouriteUpdateFolder: "/maf/app/favourites/update/folder",
		favouriteUpdateDocument: "/maf/app/favourites/update/document",
		favouriteUpdateSearch: "/maf/app/favourites/update/search",
		favouriteCreateFolder: "/maf/app/favourites/create/folder",
		favouriteCreateSearch: "/maf/app/favourites/add/search",
		favouriteCreateDocument: "/maf/app/favourites/add/document",
		favouriteRemove: "/maf/app/favourites/remove",
		resultList: "/maf/app/resultList",
		documentDisplay: "/maf/app/document"
	},
 	resize: function(e) {
 		var ll = laley;
 		var byId = getById;
 		var con = $("#service #content")[0];
 		var acc = byId("accordion");
 		var ftx = byId("fullText");
 		if (con && jQuery.browser.msie) {
 			con.style["width"] = $(window).width() - 59 + "px";
 		}
 		if (acc && con && ftx) {
	 		if (jQuery.browser.msie) {
	 			acc.style["position"] = "absolute";
		 		ll.resizeTextWidthIE(con, acc, ftx);
		 	} else {
		 		ll.resizeTextWidth(con, acc, ftx);
		 	}
	 		ll.resizeTextHeight(acc, ftx);
	 	} else if (!acc && con && ftx && jQuery.browser.msie) {
	 		ll.resizeResultList(con, ftx);
	 	}
 	},
	resizeResultList: function(con, ftx) {
 		var tW = $(window).width();
		ftx.style["width"] = tW - 95 + "px";
	},
 	resizeTextWidthIE: function(content, accordion, fulltext) {
 		var tW = $(window).width();
 		var minAccW = 150;
 		var accW = Math.floor(tW * 0.25);
 		accW = accW < minAccW ? minAccW - 20 : accW - 20;
 		var accStyle = accordion.style;
 		accStyle["width"] = accW + "px";
 		if (jQuery.browser.msie && jQuery.browser.version >= 7) {
	 		accStyle["left"] = "33px";
	 	} else {
	 		accStyle["left"] = "23px";
	 	}
 		var fulltextW = tW - accW;
 		var fullTextStyle = fulltext.style;
 		fullTextStyle["width"] = fulltextW - 100 + "px";
 		fullTextStyle["paddingLeft"] = accW + 15 + "px";
 	},
 	resizeTextWidth: function(content, accordion, fulltext) {
 		var contentW =  content.offsetWidth;
 		var minAccW = 150;
 		var accW = Math.floor(contentW * 0.25);
 		accW = accW < minAccW ? minAccW - 20 : accW - 20;
 		var fulltextW = contentW - accW - 30;
 		var accStyle = accordion.style;
 		accStyle["width"] =  accW + "px";
 		if (jQuery.browser.msie) {
 			accStyle["left"] = "23px";
 		}
 		var fulltextStyle = fulltext.style;
 		//fulltextStyle["width"] = fulltextW - 5 + "px";
 		fulltextStyle["marginLeft"] = accW + 10 + "px";
 	},
	resizeTextHeight: function(accordion, fulltext) {
		fulltext.style["height"] = "auto";
		var accH = accordion.offsetHeight;
		var ftxH = fulltext.offsetHeight;
		if (jQuery.browser.msie && jQuery.browser.version < 7) {
			//$("#content").unbind().resize(res);
			laley.resizeLite();
		} else {
			fulltext.style["minHeight"] = accH + "px";
		}
	},
	resizeLite: function() {
		var ft = getById("fullText").offsetHeight;
		var ac = getById("accordion").offsetHeight;
		var premium = $(".contPremium").height() + $("#bBottomPrem").height(); 
		var dt = $("#fullCont").height() + $("#bBottomDt").height();
		var atp = $("#atpWrapper").height() + $("#bBottomATP").height();
		
		if (laley.resizedOnce) return;
		if (ft > ac) {
			if (ft - (premium + dt + atp) > ac) {
				getById("fullText").style["paddingBottom"] = "10px";
			} else {
				getById("fullText").style["paddingBottom"] = (ac - ft + premium + dt  + atp + 30) + "px";
			}		
		} else {
			if (ft - (premium + dt + atp) < ac) {
				getById("fullText").style["paddingBottom"] = (ac - ft + premium + dt + atp + 30) + "px";
			} else {
				getById("fullText").style["paddingBottom"] = (ac - ft) + "px";
			}
		}
		laley.resizedOnce = true;
	},
	hiddenMenus: {},
	init: function() {
	
		var byId = getById;
		
		var acc = byId("accordion");
		if(acc && $(acc).css("display") != "block") {
			$(byId("fullText")).css({width : "96.5%"});
		}
		
		var err = byId("error");
		if(err && $(err).css("display") == "block") {
			$("#busqueda").css({marginTop : "0px"});
		}

		$("#columnLeft .tocItem:last").css({borderBottom : "none"});
		$("#columnRight .tocItem:last").css({borderBottom : "none"});

		if ($(".tocItem h3").css("display") != "block"){
			$(".tocItem").css({borderBottom : "none"});
			$(".tocItem p").addClass('pBorder');
		}
		
		$("div.economicas .serviceJur").hover(function(){
			$(this).addClass('borderHover');
		}, function(){
			$(this).removeClass('borderHover');
		});
		$("div.juridicas .serviceEcon").hover(function(){
			$(this).addClass('borderHover2');
		}, function(){
			$(this).removeClass('borderHover2');
		});
		
		$(".hideableMenuShower").click(function() {
			if(!laley.hiddenMenus[this.id]) {
				laley.hiddenMenus[this.id] = {
					shown: false,
					element: $("#" + this.id + "Menu")
				};
			}
			if (!laley.hiddenMenus[this.id].shown)  {
				for (var i in laley.hiddenMenus) {
					if (i != this.id && laley.hiddenMenus[i].shown) {
						laley.hiddenMenus[i].element.fadeOut("fast");
						laley.hiddenMenus[i].shown = false;
					}
				}
				
				menuOffset = $("#"+ this.id).parent().offset().left;
				if(jQuery.browser.msie)
					menuOffset -= 40;
				laley.hiddenMenus[this.id].element.css("left", menuOffset);
				laley.hiddenMenus[this.id].element.fadeIn("fast");
				laley.hiddenMenus[this.id].shown = true;
			} else {
				laley.hiddenMenus[this.id].element.fadeOut("fast");
				laley.hiddenMenus[this.id].shown = false;
			}
		});
		$(".hideableMenu li p").hover(function(){
				$(this).addClass("hover");
			}, function() {
				$(this).removeClass("hover");				
		});
		
		if (jQuery.browser.msie) {
			$(byId("ie_onresize_workaround")).resize(laley.resize);
		} else {
			$(window).resize(laley.resize);
		}
		
		/* Hacks Aca !*/
		$(".noresults").dblclick(function() {
			$("#showSearchInfoHidden").show();
		});
				
		$("#searchDataForDev").dblclick(function() {
			$("#showSearchInfoHidden").show();
		});
		/* Fin HACK */
	       
	  ////////////////////////////// Breadcrumb hover ////////////////////
	
		var hoverConfig = {
		 sensitivity:2, // number = sensitivity threshold (must be 1 or higher)    
	     interval:180, // number = milliseconds for onMouseOver polling interval    
	     over:breadcrumbOver, // function = onMouseOver callback (REQUIRED)    
	     timeout:250, // number = milliseconds delay before onMouseOut    
	     out:breadcrumbOut // function = onMouseOut callback (REQUIRED)    
		}
	   
	   //breadcrumb menu divs generator
		var hrefs = $(".breadcrumb a");
    	var divs = new Array(hrefs.length);
		for(i=0; i< hrefs.length ; i++) {
            hrefs[i].setAttribute('id','breadcrumb'+i);
		    var x = document.createElement('div');
	      	x.setAttribute('id','divbreadcrumb'+i);
	      	$(x).addClass('ajaxBreadcrumb');
            $(x).hide();
			divs[i]=x;
		};		
        $(".breadcrumb a").parent("div:parent").css({'z-index':129});
        $(".breadcrumb a").parent("div:parent").append(divs);

       /// to hide divs in a Chrome compatible way
        for(i = 0; i < divs.length; i++ ) {
	        $(divs[i]).hide();
    	}     	


	    var isHideMenuDiv = true;    		// Used to show the div while hovering either the breadcrumb or the div
	    var isSessionExpired=false;    // Used to know if a session has timeout. 
	    
	    
       ////////// HACK for IE 6 and below showing over breadcrumb menu	    
	    //IE6 hack to hide comboboxes  theVisibility == 'hidden' or 'visible'
		function toggleIE6Boxes(theVisibility) {
			if($.browser.msie && /6.0/.test(navigator.userAgent)) {
   		 		for(var i = 0; i < document.forms.length; i++) {
   		     		for(var e = 0; e < document.forms[i].length; e++){
       		   		    if(document.forms[i].elements[e].tagName == 'SELECT') {
               		        document.forms[i].elements[e].style.visibility=theVisibility;
		                }
    		    	}
		    	}
			}
		}

	// creates the timeOutDiv, not branded though !!
	function createTimeOutDiv(div){
			$(div).empty();
	      	$(div).append('<p><h2>Su sesi&#243;n finaliz&#243; por inactividad</h2> <a href="/maf/app/authentication/formLogin" xmlns="">Comenzar una nueva sesi&#243;n</a> </p>');
	      	$(div).height($(div).height() + 20);
	}

	// prunning URL parameters method
    function removeCrumbAction(strHref){
      var strReturn = "";
      if ( strHref.indexOf("&crumb-action") > -1 ){
      	str = strHref.split("&crumb-action");      	
      	return str[0];
      }
	 return strHref;
    }

	///// Parsing URL Parameters
    function getURLParam(strParamName,strHref){
      var strReturn = "";
      if ( strHref.indexOf("?") > -1 ){
        var strQueryString = strHref.substr(strHref.indexOf("?"));
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
          if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ) {
            var aParam = aQueryString[iParam].split("=");
            strReturn = aParam[1];
            break;
          }
        }
      }
      return unescape(strReturn);
    }
    

	///Breadcrumb enhancer removing span images and NoAccess links, placing "comas" correctly in summary, adding ending class for treeview.
 
	function breadcrumbMenuEnhancer(div) {

   		$(" .imageContainer", div).remove();  //removes images (only links en breadcrumb menu) 
  		$(" .tocItem:has(a)", div).addClass("doNotRemove"); //Mark non removable divs
  		$(" .tocItem:not(.doNotRemove)", div).remove(); //remove remobable. 

		var tam = $("p", div).size()-1;
		$(" .doNotRemove p", div).each(function(j) {
			if (j==tam) {$(this).addClass('breadLast')}; 
			var divpos = $(this).children().size();
   		 	$(" .noAccess", this).remove(); //remove all no access links & containers
			if (divpos > 1) { //summary
	     		for (var i  = 0; i < divpos; i++) {	     		//remove bad placed ","
	    	 		var t = $(this).html().replace(',','');
    	 			$(this).html(t);
    		 	}
   		 // no more outside commas. 
   		 	$(this).children(':not(:last)').each(function (x) {   //adds "," in between
   	 			$(this).append(',');
   		 		});
   		 	}
	 	});
	 	$("a", div).each(function (s) {
	 		var str = $(this).attr("href");
	 		var finalStr=removeCrumbAction(str); 
	 		$(this).attr("href", finalStr);
	 	});	 	
	 }
	
	//process the div.
	function ajaxDivHandler(div) {
		if ($("#time-out", div).length > 0) {  //according to jquery, if id = timeout (non intuitive by the way...) 
			isSessionExpired=true;
		}
		if (isSessionExpired) {
			// mostrar el div en posición posta! 
			createTimeOutDiv(div);
		}
		else {
    		breadcrumbMenuEnhancer(div);
    	}
	}

	// shows the menu
	function menuShow(div) {
		if ($(div).text()!= "" && $(div).text()!= "\n") {
	     	$(div).slideDown(400);
	   		toggleIE6Boxes('hidden');
     	}
     }	

	//  When mouse over breadcrumb	
    function breadcrumbOver() {    
		var params = {};		
		var datos;
		//here everything not starting with tocacction should be excluded
   		if ($(this).attr("href").indexOf("app/tocectory") > -1 ) {

			var urlAjax = getURLParam("ao",$(this).attr("href"));
			params["ao"] = urlAjax;	
			params["no-context"] = 'true';
	        var idDiv = ($(this).attr("id"));
	       	var div = ("#div"+idDiv);
	       	$(div).css({left: $(this).offset().left-8});   //Menu div position 
            if ($.browser.msie && jQuery.browser.version < 8) {$(div).css({top: $(this).offset().top-112+$(this).height()});}   //IE top position
            else {$(div).css({top: $(this).offset().top-105+$(this).height()});}  // Non IE top position
	       	
	        var divi = document.createElement('div');	
	    	if (!$(div).attr("retrieved")) {
	    		jQuery.get("/maf/app/ajaxtocectory", params, function(data){
	    			$(div).html(data);
	    			$(div).attr("retrieved","true");
			     	ajaxDivHandler(div);
	    			menuShow(div);
				});
			} 
			else menuShow(div);	
		}
	}
	
	//When mouse out of breadcrumb
	function breadcrumbOut() {
       var idDiv = ($(this).attr("id"));		
       var div = ("#div"+idDiv);       
       if (isHideMenuDiv == true) {
       		toggleIE6Boxes('visible');
    		$(div).slideUp(150);	
       }	       
    }
	
	// Hack to show new div. 
    $(".breadcrumb div").hover(function(){
		isHideMenuDiv= false;		
    },function(){
   		toggleIE6Boxes('visible');  
        $(this).slideUp(200);
    	isHideMenuDiv=true;
     });    	

	$(".breadcrumb a").hoverIntent(hoverConfig);

	//////////////////////// BreadCrumb End ///////////////////////////
	
	
	},
	
	closeClueTip: function(e) {
		if (e.target.className != "showTip" && $(e.target).parents("#cluetip").length == 0) {
			$("#cluetip").fadeOut();
		}
	},
		
	closeHidableMenu: function(e) {
		if (e.target.className != "hideableMenuShower" && $(e.target).parents(".hideableMenu").length == 0 && $(e.target).parents(".hideableMenuShower").length == 0) {
			for (var i in laley.hiddenMenus) {
				if (laley.hiddenMenus[i].shown) {
					laley.hiddenMenus[i].element.fadeOut();
					laley.hiddenMenus[i].shown = false;
				}
			}
		}
	},
	closeDocVisit: function(e) {
			
		if (e.target != document.getElementById("docVisitID") && e.target != document.getElementById("imgID")) {
			$(".docVisitContent").slideUp("fast");
			$('span.docVisitTitle img').attr({'src':'/images/documents/bt-down-doc-vis-cached.gif'}); 
			$("#errorMsgDocVisit").css({display:'none'});
		}		
	},
	utils: {
		normalizeSpace: function(text) {
			return text ? text.replace(/[ \n\t]+/g, " ") : "";
		},
		replaceInvalidChars: function(str) {
			var res = "";
			var map = {
				'\u00E1':'a', 
				'\u00E9':'e', 
				'\u00ED':'i', 
				'\u00F3':'o', 
				'\u00FA':'u'  
			};
			for (var i  = 0; i < str.length; i++) {
				var act = str.charAt(i);
				var rep = map[act];
				res += rep ? rep : act;
			}
			return res;
		},
		inArray: function(array, value) {
			if (!array) return;
			var flag = -1;
			for (var i = 0; i < array.length && flag < 0; i++) {
				if (array[i] == value) flag = i + 1;
			}
			if (flag > 0) {
				return {pos: flag};
			} else {
				return;
			}
		},
		getParamFromQuery: function(paramName, query) {
			paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			var regex = new RegExp("[\\?&]" + paramName + "=([^&#]*)");
			var results = regex.exec(query);
			if (results === null) {
				return "";
			} else {
				return results[1];
			}
		},
		UTF8: {
			encode: function(s){
				for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
					s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
				);
				return s.join("");
			},
			decode: function(s){
				for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
					((a = s[i][c](0)) & 0x80) &&
					(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
					o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
				);
				return s.join("");
			}
		},			
		modal: {
			show: function(elem) {
				if ($("#overlay").length < 1) {
					var overlay = $("body").append("<div id='overlay'></div>").children("#overlay");
				}	else {
					var overlay = $("#overlay");
				}
				
				if (jQuery.browser.msie) {
					var docW = document.body.offsetWidth;
					var winW = $(window).width();
					var docH = document.body.offsetHeight;
					var winH = $(window).height();
					var finalW = 0;
					var finalH = 0;
					if (docW > winW) {
						finalW = docW;
					}	else {
						finalW = winW;
					}
					if (docH > winH) {
						finalH = winH + 500;
					}	else {
						finalH = winH;
					}
					var body = $(document.body);
					overlay.css({
						height: finalH +
						parseInt(body.css("marginTop")) +
						parseInt(body.css("marginBottom")) +
						"px",
						width: finalW +
						parseInt(body.css("marginLeft")) +
						parseInt(body.css("marginRight")) +
						"px",
						position: "absolute"
					});
				}	else {
					overlay.css({
						height: "100%",
						width: "100%",
						position: "fixed"
					});
				}
				overlay.css({
					display: "block",
					top: "0",
					left: "0",
					backgroundColor: "black",
					opacity: "0.5",
					zIndex: "500"
				});
				
				var notif = elem.clone();
				
				notif.get(0).id = "notification";
				notif.addClass("notification").css({
					zIndex: "501"
				}).show();
				
				$("body").append(notif);
				
				if (jQuery.browser.msie) {
					var optHeight = document.documentElement.scrollTop + ($(window).height() - notif.height()) / 2;
					if (optHeight < 0) optHeight = 0;
					notif.css({
						position: "absolute",
						top: optHeight + "px",
						left: ($(window).width() - notif.width()) / 2 + "px"
					});
					
					function center(){
						$("#notification").css({
							position: "absolute",
							top: document.documentElement.scrollTop + ($(window).height() - notif.height()) / 2 + "px",
							left: ($(window).width() - notif.width()) / 2 + "px"
						});
					}
					/*$(window).bind("scroll", center);
					$(window).bind("resize", center);*/
				}	else {
					var optHeight = ($(window).height() - notif.height()) / 2;
					if (optHeight < 0) optHeight = 0;
					notif.css({
						position: "absolute",
						top:  optHeight + "px",
						left: ($(window).width() - notif.width()) / 2 + "px"
					})
				}
				this.notification = notif.css({
					display: "block"
				});
				
				overlay.bgiframe();
				this.notification.bgiframe();
			},
			hide: function(){
				$("#overlay").hide();
				$("#notification").remove();
			}
		}
	}
};

if (window.jQuery) $(document).ready(laley.init);
if (window.jQuery) $(document).click(laley.closeHidableMenu);
if (window.jQuery) $(document).click(laley.closeClueTip,function(){});
//if (window.jQuery) $(document).click(laley.closeDocVisit);