/**
 * @author	 		mel
 * Date created: 	13-02-2007 10:10 
 * Date revised: 	27-02-2007 09:39
*/

/**
 * The Apotek object 
 * Objects: upper camel case
 * Methods & properties: lower camel case
*/
var j$ = jQuery.noConflict();

var Apotek = {
	
	debug:true,
	
	/**
	 * This method returns a reference to an HTML element
	 * @param	{String} sId The id-attribute of the HTML element you want to find
	 * @returns 	A reference to the node
	*/
	$:function (sId){
		return document.getElementById(sId)!=null?document.getElementById(sId):false;
	},
	
	/**
	 * A method to easily create new DOM objects and populate them with attributes
	 * @param	{String} sType The type of HTML element to create
	 * @param	{Object} oConfig An object with attributes to attach to the created element
	 * @returns 	The newly created element
	*/
	createElement:function (sType,oConfig){
		var elm = document.createElement(sType);
		for(p in oConfig){
			if(p == "CSSClass"){
				elm.className = oConfig[p];
			} else if(p == "content"){
				try {
					elm.innerHTML = oConfig[p];
				} catch(e){}
			} else {
				elm.setAttribute(p,oConfig[p]);
			}
		}
		document.body.appendChild(elm);
		return elm;
	},

	/**
	 * Works like getElementsByTagName
	 * @param {Node} oParent The object in which you wish to find the elments
	 * @param {String} sClassName The name of the class attribute you wish to find
	 * @returns An array of elements
	*/
	getElementsByClassName:function(oParent,sClassName){
		var aNodes = oParent.getElementsByTagName("*");
		var aRet = [];
		for(var i=0; i<aNodes.length; i++){
			var sTmp = "#" + aNodes[i].className + "#";
			var sRegEx = "[ |#]" + sClassName + "[ |#]";
			if(sTmp.match(new RegExp(sRegEx))){ 
				aRet.push(aNodes[i]);
			}
		}
		return aRet;
	},
	
	/**
	 *
	*/
	addClassName:function(elem,sClassName){
	    Apotek.removeClassName(elem,sClassName);
	    elem.className = (elem.className + " " + sClassName).trim();
	},
	
	/**
	 *
	*/
	removeClassName:function(elem,sClassName){
		if(elem){
		    elem.className = elem.className.replace(sClassName,"").trim();
		}
	},
	
	/**
	 *
	*/
	toggleClassName:function(elem,sClassName){
		if(elem){
			if(elem.className.indexOf(sClassName) != -1){
			    elem.className = elem.className.replace(sClassName,"").trim();
			} else {
			    Apotek.addClassName(elem,sClassName);
			}
		}
	},
	
	/**
	 *
	*/
	hide:function(sId){
		if(sId){
		    this.$(sId).style.display = "none";
		}
	},
	
	/**
	 *
	*/
	show:function(sId){
		if(sId){
		    this.$(sId).style.display = "block";
		}
	},
	
	/**
	 *
	*/
	css:function(sId,oRules){
		if(sId){
			if(typeof oRules == "object"){
				for(p in oRules){
					Apotek.$(sId).style[p] = oRules[p];
				}
			}
		}
	},
	
	/**
	 *
	*/
	getStyle:function(o,prop){
		var ret;
		if(o.style[prop]){
			ret = o.style[prop];
		} else if(document.defaultView && document.defaultView.getComputedStyle){
			var cur = document.defaultView.getComputedStyle(o, null);
			if(cur) ret = cur.getPropertyValue(prop);
		} else if(o.currentStyle){
			var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});
			ret = o.currentStyle[prop] || o.currentStyle[newProp];
		}
		return ret;
	},
		
	/**
	 * This method will return a absolute pixel value of an element left edge to the edge of the browserwindow
	 * @param	{Node} o The HTML element which offset you want to find
	 * @returns 	A number
	*/
	getAbsLeft:function (o){
		var iY = 0;
		while(o.offsetParent){
			iY += o.offsetLeft;
			o = o.offsetParent;
		}
		return iY;
	},

	/**
	 * This method will return a absolute pixel value of an element top edge to the edge of the browserwindow
	 * @param	{Node} o The HTML element which offset you want to find
	 * @returns 	A number
	*/
	getAbsTop:function (o){
		var iX = 0;
		while(o.offsetParent){
			iX += o.offsetTop;
			o = o.offsetParent;
		}
		return iX;
	},
	disableFirebugConsoleInIE:function (){
		try {
			if(!window.console){
				window.console = {}
				var m = ["debug","info","warn","error","assert","dir","dirxml","trace","group","groupEnd","time","timeEnd","profile","profileEnd","count"];
				for(var i=0; i<m.length; i++){
					window.console[m[i]] = function(){return false;};
				}
			}
		} catch(e){}
	},
	
	/**
	 * 
	*/
	Browser:{
		safari:/webkit/.test(navigator.userAgent.toLowerCase()),
		opera:/opera/.test(navigator.userAgent.toLowerCase()),
		msie:/msie/.test(navigator.userAgent.toLowerCase()) && !/opera/.test(navigator.userAgent.toLowerCase()),
		mozilla: /mozilla/.test(navigator.userAgent.toLowerCase()) && !/(compatible|webkit)/.test(navigator.userAgent.toLowerCase())
	},
	
	/**
	 * 
	*/
	Page: {
		AccessiblePopupLinks:{
			initialize:function (){
				
				var dims = {
				    basic:{w:710,h:560,scroll:0},
				    mega:{w:1000,h:1000,scroll:0},
				    defaultDims:{w:50,h:50,scroll:0}
				}
				var currentDims = "";

				var links = Apotek.getElementsByClassName(document,"popup");
				for(var i=0; i<links.length; i++){
					var o = links[i];
					var sHref = o.getAttribute("href");
					o.setAttribute("savedHrefAtt",sHref); // save the href attribute so we can use it in the window.open()
					o.setAttribute("savedClassName",o.className); // save the href attribute so we can use it in the window.open()
					o.onclick = function (){
						if(sHref != "#" && sHref != ""){
						    if(this.getAttribute("savedClassName").indexOf("basic") != -1){
    					        currentDims = "basic";
						    } else if(this.getAttribute("savedClassName").indexOf("mega") != -1){
						        currentDims = "mega";
						    } else { 
						        currentDims = "defaultDims";
						    }
						    //alert(this.getAttribute("savedClassName"))
							var win = window.open(this.getAttribute("savedHrefAtt"),"Apotek","width="+dims[currentDims].w+",height="+dims[currentDims].h+", resizable = " + dims[currentDims].scroll + ", scrollbars = " + dims[currentDims].scroll);
						}
						return false; 
					};
				} // end for()
			}
		}, // @Apotek.Page.AccessiblePopupLinks
		
		Tables:{
			Zebra:{
				initialize:function (){
					Apotek.Page.Tables.Zebra.regular();
					Apotek.Page.Tables.Zebra.multipleItems();
				},
				regular:function (){
					var oTables = Apotek.getElementsByClassName(document,"stripes");
					for(var i=0; i<oTables.length; i++){
						if(oTables[i].className.indexOf("stripes") != -1){
							var oTbodys = oTables[i].getElementsByTagName("TBODY");
							for(var j=0; j<oTbodys.length; j++){
								for(var k=0; tr=oTbodys[j].getElementsByTagName("TR")[k]; k++){
									if(tr.className.length <= 0){
										tr.className = k%2==0?"odd":"even";
									}
								}
							}
						}
					}
				},
				/*
				multipleItems:function (){
					var oTables = Apotek.getElementsByClassName(document,"stripes-multiple-items");
					for(var i=0; i<oTables.length; i++){
						var oTbodys = oTables[i].getElementsByTagName("TBODY");
						for(var j=0; j<oTbodys.length; j++){
							for(var k=0; tr=oTbodys[j].getElementsByTagName("TR")[k]; k++){
								if(tr.className.length <= 0){
									tr.className = j%2==0?"odd":"even";
									if(k==0&&oTbodys[j].className=="multiple"){
										tr.className += " addborder";
									}
								}
							}
						}
					}
				} */
				// Ćndret af EKO, 10/4/2007
				multipleItems:function (){
					var oTables = Apotek.getElementsByClassName(document,"stripes-multiple-items");
					for(var i=0; i<oTables.length; i++){
						var oTbodys = oTables[i].getElementsByTagName("TBODY");
						for(var j=0; j<oTbodys.length; j++){
						    var m = 0;
							for(var k=0; tr=oTbodys[j].getElementsByTagName("TR")[k]; k++){
								var cl = "";									
								if(tr.className=="multiple"){
									m += 1;
									cl = " addborder";
								}
								tr.className = "multiple " + (m%2==0?"even":"odd") + cl;
							}
						}
					}
				}
			}
		}, // @Apotek.Page.Tables.zebratize
					
		Tooltips:{
			initialize:function (){
				
				$(".tooltip-text").hide();
				$(".tooltip-text").css({visibility:"hidden"});
				$(document).click(function (){ try { $(".tooltip-text").hide(); } catch(e){} });

				$(".tooltip").each(function (){
					$(this).click(function (e){
						$(".tooltip-text").hide();
						$(".tooltip-text",this).show();
						$(".tooltip-text",this).css({visibility:"visible"});
						var i = $(".tooltip-text",this).get(0);
						$(".tooltip-text",this).top("-"+(i.offsetHeight-5)+"px");
						if(!e) var e = window.event;
						if(e.stopPropagation){
							e.stopPropagation();
						} else {
							e.cancelBubble = true;
						}
					});
				});
				
			}
		}, // @Apotek.Page.Infobox

MouseOverImage:{
   initialize:function (){
                         
     var a = Apotek.getElementsByClassName(document,"mo-init");
     for(var i=0; i<a.length; i++){
           a[i].counter = i;
           a[i].onmouseover = function (){
                                 if(this.getAttribute("tgId") != null){
                                                       Apotek.show(this.getAttribute("tgId"));
                                 } else {
                                                      var tg = Apotek.getElementsByClassName(this.parentNode.parentNode,"mo-tg");
                                                     if(tg.length > 0){
                                                                            this.setAttribute("tgId","mo-"+this.counter);
                                                                            tg[0].id = "mo-"+this.counter;
                                                                            tg[0].style.display = "block";
                                                      }
                                 }
                                 Apotek.$(this.getAttribute("tgId")).style.position = "absolute";
                                 Apotek.$(this.getAttribute("tgId")).style.left = (Apotek.getAbsLeft(this) + this.offsetWidth) + "px";
                                 Apotek.$(this.getAttribute("tgId")).style.top = (Apotek.getAbsTop(this)) + "px";
           }
           a[i].onmouseout = function (e){
                                 if(this.getAttribute("tgId") != null){
                                                       Apotek.hide(this.getAttribute("tgId"));
                                 }
           }
     }
   }
}, // @Apotek.Page.MouseOverImage


		
		Cookie:{
			create:function(name,value,days){
				if(days){
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					var expires = "; expires="+date.toGMTString();
				} else {
					expires = "";
				}
				document.cookie = name+"="+value+expires+"; path=/";
			},
			read:function(name){
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i<ca.length; i++){
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if(c.indexOf(nameEQ)==0) return c.substring(nameEQ.length,c.length);
				}
				return null;
			}
		}, // @Apotek.Page.Cookie
		
		print:function (){
			try {
				window.print(); 
			} catch(e){}
			return false;
		}, // @Apotek.Page.Print
		
		Forms:{
			initialize:function (){
				try {
					if(Apotek.$("btn-select-all")) Apotek.$("btn-select-all").style.display = "inline";
				} catch(e){ if(Apotek.debug) alert(e.message); }
			},
			emptyOnFocus:function (oThis){
				try {
					oThis.value = "";
				} catch(e){}
			},
			toggleCbs:function (sTableId,btn){
				var cbs = Apotek.$(sTableId).getElementsByTagName("input");
				for(var i=0; i<cbs.length; i++){
					var cb = cbs[i];
					if(cb.type == "checkbox" && cb.className.indexOf("toggle-target") != -1){
						if(cb.getAttribute("state") == null || cb.getAttribute("state") == "off"){
							cb.checked = "checked";
							cb.setAttribute("state","on");
							btn.value = "Afmarkér alle";
						} else {
							cb.checked = "";
							cb.setAttribute("state","off");
							btn.value = "Markér alle";
						}
					}
				}
			}
		}, // @Apotek.Page.Forms
		
		Layout:{
			resizeRightCol:function (){
				if($("#col-right-inner").id()){
					var rightColOffsetTop = document.getElementById("basket").offsetHeight;
					var contentHeight = document.getElementById("meat").offsetHeight;
					$("#col-right-inner").css("height",contentHeight-rightColOffsetTop+"px");
				}
			}
		}, // @Apotek.Page.Layout
		
		/**
		 * onDOMContentLoaded crossbrowser, kudos jquery
		*/
		Loader:{
			readyList:[],
			add:function (func){
				Apotek.Page.Loader.readyList.push(func);
			},
			run:function (){
				for(var i=0; i<Apotek.Page.Loader.readyList.length; i++){
					Apotek.Page.Loader.readyList[i].apply(document);
				}
			},
			prepare:function (){
				if (Apotek.Browser.mozilla || Apotek.Browser.opera){
					document.addEventListener( "DOMContentLoaded", Apotek.Page.Loader.run, false );
				} else if(Apotek.Browser.msie){	
					// If IE is used, use the excellent hack by Matthias Miller
					// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
				
					// Only works if you document.write() it
					document.write("<scr" + "ipt id=__ie_init defer=true " + 
						"src=//:><\/script>");
				
					// Use the defer script hack
					var script = document.getElementById("__ie_init");
					
					// script does not exist if jQuery is loaded dynamically
					if ( script ) 
						script.onreadystatechange = function() {
							if ( this.readyState != "complete" ) return;
							this.parentNode.removeChild( this );
							Apotek.Page.Loader.run();
						};
				
					// Clear from memory
					script = null;
				} else if (Apotek.Browser.safari){
					// Continually check to see if the document.readyState is valid
					var safariTimer = setInterval(function(){
						// loaded and complete are both valid states
						if ( document.readyState == "loaded" || 
							document.readyState == "complete" ) {
				
							// If either one are found, remove the timer
							clearInterval(safariTimer);
							safariTimer = null;
				
							// and execute any waiting functions
							Apotek.Page.Loader.run();
						}
					}, 10); 
				} else {
					// A fallback to window.onload, that will always work
					Apotek.addLoadEvent(Apotek.Page.Loader.run);
				}
			}	
		},
		logPaaFunc:{
		    logPaaTabs:function(){
			    var tabNav = j$("#tabNav");
			    var tabContentContainer = j$("#tabContentContainer");
			    j$(tabNav).find("li.tab a").click(function(e){
				    e.preventDefault();
				    j$(tabNav).find("li.tabActive").removeClass("tabActive");
				    j$(tabContentContainer).find("div.tabContentActive").removeClass("tabContentActive");
				    j$(this).parent().addClass("tabActive");
				    j$(j$(this).attr("href")).addClass("tabContentActive");
			    });
			},
			logPaaHusk:function(){
			    var tabContentContainer = j$("#tabContentContainer");
			    j$(tabContentContainer).find("input:checkbox").click(function(){
			        if(this.checked === true){
			            if((this.id).indexOf("huskNemID") !== -1){
			                j$(tabContentContainer).find("input:checked:not(input[id$=huskNemID])").attr('checked', function() {
			                    return !this.checked;
			                });
			                Apotek.Page.Cookie.create("huskLogPaa","NemID",365);
			            } else if((this.id).indexOf("huskDigital") !== -1){
			                j$(tabContentContainer).find("input:checked:not(input[id$=huskDigital])").attr('checked', function() {
			                    return !this.checked;
			                });
			                Apotek.Page.Cookie.create("huskLogPaa","Digital",365);
			            } else if((this.id).indexOf("huskUden") !== -1){
			                j$(tabContentContainer).find("input:checked:not(input[id$=huskUden])").attr('checked', function() {
			                    return !this.checked;
			                });
			                Apotek.Page.Cookie.create("huskLogPaa","Uden",365);
			            }
			        } else {
			            Apotek.Page.Cookie.create("huskLogPaa","",1);
			        }
			    });
		    },
		    init:function(){
		        Apotek.Page.logPaaFunc.logPaaTabs();
		        Apotek.Page.logPaaFunc.logPaaHusk();
		        var huskLog = Apotek.Page.Cookie.read("huskLogPaa");
		        if(huskLog == "NemID"){
		            j$("#tabContentContainer").find("input[id$=huskNemID]").attr('checked','checked');
		        } else if(huskLog == "Digital"){
		            j$("#tabNav a[href=#logPaaDigital]").trigger("click");
		            j$("#tabContentContainer").find("input[id$=huskDigital]").attr('checked','checked');
		        } else if(huskLog == "Uden"){
		            j$("#tabNav a[href=#logPaaUden]").trigger("click");
		            j$("#tabContentContainer").find("input[id$=huskUden]").attr('checked','checked');
		        }
		    }
		},
		start:function (){

			/**
			 * 
			*/
			Apotek.Page.AccessiblePopupLinks.initialize();
			
			/**
			 * Adds alternating row colors to tables with class="stripes".
			*/
			Apotek.Page.Tables.Zebra.initialize();
			
			/**
			 * 
			 */
			Apotek.Page.Forms.initialize();
			
			Apotek.Page.MouseOverImage.initialize();
		} // @Apotek.Page.start
		
	} // @Apotek.Page
} // @Apotek


/**
 * Initialize the document
*/
Apotek.Page.Loader.prepare();
Apotek.Page.Loader.add(Apotek.Page.start);

 j$().ready(function(){ Apotek.Page.logPaaFunc.init();})
/**
 * Add some prototypes to native objects
*/
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/,"");
}
if(typeof Array.prototype.push == "undefined"){ // ie5
	Array.prototype.push = function (k){
		this[this.length] = k;
		return this.length;
	};
}

function OpenDrugImageWindow( imageId ) 
{	
  var drugImageWin ;
	
	drugImageWin = window.open( '/layouts/apoteket/apo.medicinehandbookimage.aspx?imageIdentifier=' + imageId, '_blank', 'width=453,height=227,scrollbars=no,resizable=no,addressbar=no', true ) ;
	
	drugImageWin.focus() ;
}





var App = {};
App.Corners = {
  init:function(){
    j$("img.corners,div.corners img").each(function (){
      var floating = "none ";
      if(j$(this).hasClass("left") || j$(this).css("float") == "left" || j$(this).attr("align") == "left"){
        floating = "left ";
      }
      if(j$(this).hasClass("right") || j$(this).css("float") == "right" || j$(this).attr("align") == "right"){
        floating = "right ";
      }
      j$(this).wrap("<span class='"+floating+"corners' style='width:"+j$(this).width()+"px;height:"+j$(this).height()+"px;'></span>");
      j$(this).after("<img src='/images/corner_se_white.png' class='corner br' /><img src='/images/corner_sw_white.png' class='corner bl' /><img src='/images/corner_ne_white.png' class='corner tr' /><img src='/images/corner_nw_white.png' class='corner tl' />");
      //j$(this).after("<img src='/images/corners/c_br.png' class='corner br' /><img src='/images/corners/c_bl.png' class='corner bl' /><img src='/images/corners/c_tr.png' class='corner tr' /><img src='/images/corners/c_tl.png' class='corner tl' />");
    });
  }
};

j$(App.Corners.init);

var measure = 0;
function setHighest(number){
    if(number > measure){
        measure = number;
    }
}
function adjustULHeights(){
  j$(".katlist li").each(function (){
      setHighest(this.offsetHeight);
      if(j$(this).hasClass("last")){
          j$(this).css("height",measure + "px")
          measure = 0;
      }
  });
}
j$(adjustULHeights);

function addLinkToListImage(){
  j$("ul[class*=katlist] li").each(function (){
    var link = j$(this).find("a").eq(0);
    if(link){
      var href = link.attr("href");
      j$(this).addClass("mimicLink").click(function (){
        window.location = href;
      });
    }
  });
}
j$(addLinkToListImage);




