/**
 * The Sonofon object 
 * Objects: upper camel case
 * Methods & properties: lower camel case
*/
var Sonofon = {
	
	/**
	 * 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;
	},
	/**
	 * 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){}
	},
	disableIEBackgroundFlicker:function (){
		try { document.execCommand('BackgroundImageCache', false, true); } catch(e){}
	},
	
	/**
	 * 
	*/
	Page: {
		Tables:{		
			zebratize:function (){
				var oTables = $(".stripes");
				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++){
							tr.className = k%2==0?"odd":"even";
						}
					}
				}
			}
		}, // @Sonofon.Page.Tables.zebratize
					
		Flow:{
			initialize:function (){
				$(".options").addClass("hidden");
				
				var curtains = {open:""};
				
				$("#choice01-radio").click(function (){
					if(curtains.open != this.id){
						$("#choice01-options").removeClass("hidden");
						$("#choice01-options").slideDown("slow");
						$("#choice01").removeClass("dimmed");
						if(curtains.open != ""){
							$("#choice02-options").slideUp("slow");
						}
						$("#choice02").addClass("dimmed");
						curtains.open = this.id;
					}
				});
				$("#choice02-radio").click(function (){
					if(curtains.open != this.id){
						if(curtains.open != ""){
							$("#choice01-options").slideUp("slow");
						}
						$("#choice01").addClass("dimmed");
						$("#choice02-options").removeClass("hidden");
						$("#choice02-options").slideDown("slow");
						$("#choice02").removeClass("dimmed");
						curtains.open = this.id;
					}
				});
			}
		},
		
		FAQ:{
			initialize:function (){
				$("ul#faq.expandable-link-list div.answer").hide();
				$("ul#faq.expandable-link-list div.hr-dotted").hide();
				$("ul#faq.expandable-link-list a.open").each(function (){ this.setAttribute("status","collapsed") }); // set inital attr of the link to collapsed

				$("ul#faq.expandable-link-list a.open").click(function (){
					if(this.getAttribute("status") == "collapsed"){			// check custom attr status to enable expand and collapse on the same link
						$(".answer",this.parentNode).slideDown("slow",Sonofon.Page.Layout.resizeRightCol);
						$(".hr-dotted",this.parentNode).show();
						this.setAttribute("status","expanded");				// toogle status attr
					} else {
						$(".answer",this.parentNode).slideUp("slow",Sonofon.Page.Layout.resizeRightCol);
						$(".hr-dotted",this.parentNode).hide();
						this.setAttribute("status","collapsed");
					}
					Sonofon.Page.Layout.resizeRightCol();
					return false;
				});
				$("ul#faq.expandable-link-list a.close").click(function (){
					$(this.parentNode).slideUp("slow");
					$(".hr-dotted",this.parentNode.parentNode).hide();
					$(".open",this.parentNode.parentNode).attr("status","collapsed");
					Sonofon.Page.Layout.resizeRightCol();
					return false;
				});
			}
		},
		
		GenericExpandList:{
			initialize:function (){
				$("ul.list-element-expand div.answer").hide();
				$("ul.list-element-expand div.hr-dotted").hide();
				$("ul.list-element-expand a.open").each(function (){ this.setAttribute("status","collapsed") }); // set inital attr of the link to collapsed

				$("ul.list-element-expand a.open").click(function (){
					if(this.getAttribute("status") == "collapsed"){			// check custom attr status to enable expand and collapse on the same link
						$(".answer",this.parentNode).slideDown("slow");
						$(".hr-dotted",this.parentNode).show();
						this.setAttribute("status","expanded");				// toogle status attr
					} else {
						$(".answer",this.parentNode).slideUp("slow");
						$(".hr-dotted",this.parentNode).hide();
						this.setAttribute("status","collapsed");
					}
					return false;
				});
				$("ul.list-element-expand a.close").click(function (){
					$(this.parentNode).slideUp("slow");
					$(".hr-dotted",this.parentNode.parentNode).hide();
					$(".open",this.parentNode.parentNode).attr("status","collapsed");
					return false;
				});
			}
		},
		
		Tabs:{
			imgStdPath: new Array(),
			imgSelPath: new Array(),
			tempStdPath: new Array(),
			tempSelPath: new Array(),
			deepLinkHashCollectionPrefix:"tab-coll-",
			initialize:function (){
				$(".tabs").each(function (collCount){
					var sId = Sonofon.Page.Tabs.deepLinkHashCollectionPrefix+collCount;
					$(this).attr('id',sId);
					$(this).attr("openTab",1);
					Sonofon.Page.Tabs.hideAllContent(sId);
					Sonofon.Page.Tabs.gotoTab(collCount,$(this).attr("openTab"));
					$(".tab-btn",$(this)).each(function (counter){
						//if(counter == 0){ // strange IE 6 rendering issue if not set. The first image will sit 1 px lower that the others.
						//	$("img",$(this)).css({marginTop:"-1px"});
						//}
						$(this).attr("container",collCount);
						$(this).click(function (){
							Sonofon.Page.Tabs.gotoTab($(this).attr("container"),counter+1);
						});
					});
				});
			},
			reInitTabCollection:function (o){
				$(".tabs",o).each(function (collCount){
					var sId = Sonofon.Page.Tabs.deepLinkHashCollectionPrefix+1000;
					$(this).attr('id',sId);
					$(this).attr("openTab",1);
					//$(this).attr("imgPath",Sonofon.Page.Tabs.imgPath);
					Sonofon.Page.Tabs.hideAllContent(sId);
					Sonofon.Page.Tabs.gotoTab(1000,$(this).attr("openTab"));
					$(".tab-btn",$(this)).each(function (counter){
						$(this).attr("container",1000);
						$(this).click(function (){
							Sonofon.Page.Tabs.gotoTab($(this).attr("container"),counter+1);
						});
					});
				});
                                                //CHANGES DONE BY TCS FOR CHG0017592
		                //if($.browser.msie){
                			var sc = document.getElementById(o.attr('id')).getElementsByTagName("SCRIPT");
                    			for(var i=0; i<sc.length; i++){
                        	  	  eval(sc[i].innerHTML)
                    			}
                    			this.resetImgSrc(o.attr('id'));
                    			this.gotoTab(1000,1);
		                //}
                                                //END CHANGES
   			},
			gotoTab:function (iCollection,iStep){
				var container = this.deepLinkHashCollectionPrefix+iCollection;
				this.resetImgSrc(container);
				this.hideAllContent(container);
				this.resetZIndices(container);
				this.setTopZIndex($(".tab-btn",$("#"+container)).eq(iStep-1));
				this.setImgSrc(container,iStep-1);
				$(".tab-content",$("#"+container)).eq(iStep-1).show();
				$("#"+container).attr("openTab",iStep);
				//this.addClickToHistory(iCollection,iStep);
				Sonofon.Page.Layout.resizeRightCol();
				Sonofon.Page.FloatingLayer.resizeIframe();
				return false; 
			},
			resetZIndices:function (container){
				$(".tab-btn",$("#"+container)).each(function (counter){
					$(this).css({zIndex:(100-counter)});
				});
			},
			resetImgSrc:function (container){
				$(".tab-btn img",$("#"+container)).each(function (counter){
					$(this).attr('src',Sonofon.Page.Tabs.imgStdPath[counter]);
				});
			},
			setImgSrc:function (container, i){
				$("img",$("#"+container+" .tab-btn").eq(i)).attr('src',Sonofon.Page.Tabs.imgSelPath[i]);
			},
			setTopZIndex:function (o){
				$(o).css({zIndex:101});
			},
			hideAllContent:function (sId){
				$(".tab-content",$("#"+sId)).hide();
			},
			//CHANGES DONE BY TCS FOR CHG0017592
			saveTabs:function(){
    			this.tempStdPath = (new Array()).concat(this.imgStdPath);
	    		this.tempSelPath = (new Array()).concat(this.imgSelPath);
			},
			restoreTabs:function(){
    			this.imgStdPath = this.tempStdPath;
	    		this.imgSelPath = this.tempSelPath;
			}
			//END CHANGES

		}, // @Sonofon.Page.Tabs
		
		Tooltips:{
			initialize:function (){
				
				$(".tooltip-text").hide();
				$(".tooltip-text").css({visibility:"hidden"});

				$(".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;
						}
					});
					$(this).mouseover(function (e){
						$(".tooltip-text").hide();
					});
				});
				
			}
		}, // @Sonofon.Page.Tooltips
		
		FloatingLayer:{
			initialize:function (){
				$(".xp-layer-close").each(function (){
					$(this).click(function (e){
						$(this).parent().parent().parent().parent().parent().parent().removeClass("shown");
						$(".layer-body",document.getElementById("xp-layer-2")).html("");
						if(document.getElementById("progressbar")!=null){ // only hide milkmask if we're in a flow
							Sonofon.Page.FloatingLayer.MilkMask.destroy();
						}
//CHANGES DONE BY TCS FOR CHG0017592
    					Sonofon.Page.Tabs.restoreTabs();
    					//END CHANGES
						return false;
					});
				});
			},
			show:function (oConfig){

				// ie 6 iframe/select fix
				try {
					if(1==2 && document.getElementById("ie6fix") == null){ // only create once
						var appendTo = document.getElementById(oConfig.id);
						var oIframe = Sonofon.createElement("IFRAME",{id:"ie6fix",CSSClass:"ie6fix",src:"/blank.html"});
						oIframe.style.width = appendTo.offsetWidth + "px";
						oIframe.style.height = appendTo.offsetHeight + "px";
						appendTo.appendChild(oIframe);
					}
				} catch(e){}

				$("#"+oConfig.id).addClass("shown");

				// set html of xp-layer
				if(oConfig.html != "undefined"){
				    //CHANGES DONE BY TCS FOR CHG0017592
					Sonofon.Page.Tabs.saveTabs();
					//END CHANGES
					Sonofon.Page.FloatingLayer.content({id:oConfig.id,html:oConfig.html});
					Sonofon.Page.Tabs.reInitTabCollection($("#"+oConfig.id));
				}

				// calc x pos
				var sLeft = "";
				if(typeof oConfig.left == "number"){
					sLeft = oConfig.left+"px";
				} else if(typeof oConfig.left == "string"){
					if(oConfig.left == "center"){
						var w = parseInt($("#"+oConfig.id).width());
						sLeft = (Math.round(($(window).width()/2)) - (Math.round(w/2)) ) + $(document).scrollLeft() + "px";
					}
				}

				// calc y pos
				var sTop = "";
				if(typeof oConfig.top == "number"){
					sTop = oConfig.top+"px";
				} else if(typeof oConfig.top == "string"){
					if(oConfig.top == "center"){
						var h = document.getElementById(oConfig.id).offsetHeight;
						sTop = ( Math.round(($(window).height()/2)) - (Math.round(h/2)) ) + $(document).scrollTop() + "px";
					}
				}
				//alert(sLeft + ", "+ sTop)
				if(parseInt(sLeft) < 0){ sLeft = "0px"; }
				if(parseInt(sTop) < 0){ sTop = "0px"; }
				$("#"+oConfig.id).css({left:sLeft,top:sTop});

				if(document.getElementById("progressbar")!=null){ // only show milkmask if we're in a flow
					Sonofon.Page.FloatingLayer.MilkMask.create();
				}

			},
			hide:function (oConfig){
				$("#"+oConfig.id).removeClass("shown");
				$("#"+oConfig.id).addClass("xp-offscreen");
			},
			spawn:function (oConfig){
				
			},
			clone:function (oConfig){

			},
			content:function(oConfig){
				if(typeof oConfig.html == "string"){
					$("#"+oConfig.id + " .layer-body").eq(0).html(oConfig.html);
				} else if(typeof oConfig.html == "object"){
					var devnull = document.getElementById("devnull");
					if(devnull==null){  devnull = Sonofon.createElement("DIV",{id:"devnull"}); }
					$("#"+oConfig.id + " .layer-body").html("");
					$("#"+oConfig.id + " .layer-body").eq(0).append(oConfig.html.html());
					$(devnull).append(oConfig.html);
				}
			},
			resizeIframe:function (){
				if (document.getElementById("xp-layer-2")) {
					var oXP = document.getElementById("xp-layer-2");
					var iframe = oXP.getElementsByTagName("IFRAME");
					if(iframe[0]) iframe[0].style.height = oXP.offsetHeight + "px";
				}
			},
			MilkMask:{
				ieImgUrl:"",
				create:function(){
					if (document.getElementById("col-middle")) {
						var col = document.getElementById("col-middle");
						var oDiv = Sonofon.createElement("DIV",{id:"milkmask",content:"<img src='"+this.ieImgUrl+"' />"});
						oDiv.style.height = col.offsetHeight + "px";
						oDiv.style.width = col.offsetWidth + "px";
						col.appendChild(oDiv);
						var i,j;
						for(i=0; j = col.getElementsByTagName("SELECT")[i]; i++){
							j.style.visibility = "hidden";
						}
					}
				},
				destroy:function (){
					if (document.getElementById("col-middle")) {
						var col = document.getElementById("col-middle");
						var o = document.getElementById("milkmask");
						if(o) try { col.removeChild(o); } catch(e){}
						var i,j;
						for(i=0; j = col.getElementsByTagName("SELECT")[i]; i++){
							j.style.visibility = "visible";
						}
					}
				}
			}

		}, // @Sonofon.Page.FloatingLayer
				
		Switcher:{
			show:function (oConfig){
				// flip elements in oConfig.mother
				$("#"+oConfig.mother+" .hidden").removeClass("hidden");
				return false;
			},
			hide:function (oConfig){
				// flip elements in oConfig.mother
				$("#"+oConfig.mother+" .toggle-target").addClass("hidden");
				return false;
			},
			toggleCheckBox:function (oConfig){
			                var o = oConfig.thisRef;
				if(o.getAttribute("state") != "expanded"){
				    $("#"+oConfig.mother).removeClass("hidden");
				    o.setAttribute("state", "expanded");
				} else
				{
				    $("#"+oConfig.mother).addClass("hidden");
				    o.setAttribute("state", "");
				}
				return false;
			},
			/**
			 *  @param Object - example: { mother: String [required] - the HTML-elements' id attribute, thisRef: Object [required] - reference the the calling object, swapText: String [optional] - the text to replace with, addClass: String [optional] - add this classname to the calling object, deep: Boolean [optional] - Whether or not to only toggle direct children of the calling object }
			*/
			toggle:function (oConfig){
				// flip all elements in oConfig.mother with classnames = .toggle-target.hidden
				if(typeof oConfig.mother == "string"){
					if(oConfig.deep === false){ // only direct children
						$("#"+oConfig.mother+" > .toggle-target.hidden").removeClass("hidden");
					} else { 					// all children below mother
						$("#"+oConfig.mother+" .toggle-target.hidden").removeClass("hidden");
					}
					var o = oConfig.thisRef;
					if(o.getAttribute("state") != "expanded"){
						if(oConfig.swapText != undefined){
							// save the original nodeValue in custom attribute
							o.origText = o.firstChild.nodeValue;
							o.firstChild.nodeValue = oConfig.swapText;
						}
						if(oConfig.addClass != undefined){
							$(o).addClass(oConfig.addClass);
						}
						o.setAttribute("state","expanded");
					} else {
						if(oConfig.swapText != undefined){
							o.firstChild.nodeValue = o.origText;
						}
						if(oConfig.addClass != undefined){
							$(o).removeClass(oConfig.addClass);
						}
						o.setAttribute("state","");
						
						if(oConfig.deep === false){
							$("#"+oConfig.mother+" > .toggle-target").addClass("hidden");
						} else {
							$("#"+oConfig.mother+" .toggle-target").addClass("hidden");
						}
					}
				} else {
					for(var i=0; i<oConfig.mother.length; i++){
						var elm = oConfig.mother[i];
						window.console.log(elm)
						$("#"+elm+" .toggle-target.hidden").removeClass("hidden");
						var o = oConfig.thisRef;
						if(o.getAttribute("state") != "expanded"){
							if(oConfig.swapText != undefined){
								// save the original nodeValue in custom attribute
								o.origText = o.firstChild.nodeValue;
								o.firstChild.nodeValue = oConfig.swapText;
							}
							if(oConfig.addClass != undefined){
								$(o).addClass(oConfig.addClass);
							}
							o.setAttribute("state","expanded");
						} else {
							if(oConfig.swapText != undefined){
								o.firstChild.nodeValue = o.origText;
							}
							if(oConfig.addClass != undefined){
								$(o).removeClass(oConfig.addClass);
							}
							o.setAttribute("state","");
							$("#"+elm+" .toggle-target").addClass("hidden");
						}
					} // for()
				}
				try { Sonofon.Page.Layout.resizeRightCol(); } catch(e){ }
				return false;
			}
		}, // @Sonofon.Page.Switcher
		
		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;
			}
		}, // @Sonofon.Page.Cookie
		
		Popup:function (thisRef){
			var win = window.open(thisRef.href);
			return false;
		}, // @Sonofon.Page.Popup

		print:function (){
			try {
				window.print(); 
			} catch(e){}
			return false;
		}, // @Sonofon.Page.Print
		
		Forms:{
			emptyOnFocus:function (oThis){
        	                                try {
		                   oThis.value = "";
		                   if(oThis.className.indexOf("input-em") != -1){
			       oThis.setAttribute("special-class",true);
			       oThis.className = oThis.className.replace("input-em","");
		                   }
		            
		                   if(oThis.onblur != undefined){
			     oThis.onblur = function (){
			       if(this.value == ""){
			         this.value = this.defaultValue;
			         if(this.getAttribute("special-class")){
			           this.className += " input-em";
			         }
			       }
			     }
    		                   }
 	                                 } catch(e){}
                                          }

		}, // @Sonofon.Page.Forms
		
		Layout:{
			resizeRightCol:function (){
				if($("#col-right-inner").attr('id') && ($("#basket").attr('id') || $("#ucLogin_ucLogin_Panel1").attr('id'))){
					$("#col-right-inner").css("height","auto");
					if ($("#basket").attr('id'))
						var rightColOffsetTop = document.getElementById("basket").offsetHeight;
					else
						var rightColOffsetTop = document.getElementById("ucLogin_ucLogin_Panel1").offsetHeight;
					var rightColheight = document.getElementById("col-right-inner").offsetHeight;
					var contentHeight = document.getElementById("meat").offsetHeight;
					var lessIsMore = (document.body.className.indexOf("front") != -1 ? 20 : 0);
					if (contentHeight>(rightColOffsetTop+rightColheight)) $("#col-right-inner").css("height",contentHeight-rightColOffsetTop-lessIsMore+"px");
				}
			},
			hideRightColShadowIfInFlow:function (){
				if(document.getElementById("progressbar")!=null){
					if(document.getElementById("col-right-inner")!=null)
						document.getElementById("col-right-inner").style.display = "none";
				}
			}
		}, // @Sonofon.Page.Layout
		
		start:function (){
			//Sonofon.disableFirebugConsoleInIE();
			Sonofon.disableIEBackgroundFlicker();

			/**
			 * 
			*/
			
			/**
			 * 
			*/
			Sonofon.Page.Flow.initialize();

			/**
			 * Creates all handlers for buttons and show/hide of content within a div with class="tabs".
			 * The internal structure of the HTML is extremely important to make it work. CSS classes must
			 * be typed exactly as in the prototype.
			*/
			Sonofon.Page.Tabs.initialize();

			/**
			 * Converts an ul with id="faq" and class="expandable-link-list" to an 
			 * expand/collapse list with a different appearance than the GenericExpandList.
			*/
			Sonofon.Page.FAQ.initialize();

			/**
			 * Every ul on the page with class="list-element-expand" will be converted to an expand/collapse list
			 * Appearance can be customized in the stylesheet (search for ".list-element-expand").
			 * The internal structure of the HTML is extremely important to make it work. CSS classes must
			 * be typed exactly as in the prototype.
			*/
			Sonofon.Page.GenericExpandList.initialize();

			/**
			 * Initializes all elements with class="tooltip" to show and hide an element inside the first
			 * element onclick. Appearance can be customized in the stylesheet.
			*/
			// pt. deaktiveret da den ødelægger link popup i nyt vindue
			Sonofon.Page.Tooltips.initialize();

			/**
			 * 
			*/
			Sonofon.Page.FloatingLayer.initialize();
						/**
			 * Resizes the background-image in the right column to expand all the way down to the footer.
			*/
			Sonofon.Page.Layout.resizeRightCol();
			Sonofon.Page.Layout.hideRightColShadowIfInFlow();

			
		} // @Sonofon.Page.start
		
	} // @Sonofon.Page
} // @Sonofon

    function ChangeLabelColorForValidator(val){
        var lbl = document.getElementById(val.controltovalidate + '_lbl');
        if(lbl!= null ){
            // Find label through naming rule
            var k, value;

            // Find out all validators associated
            var vals = new Array();
            for(k=0; k < Page_Validators.length; k++){
                if(Page_Validators[k].controltovalidate == val.controltovalidate)
                    vals.push(Page_Validators[k]);
            }

            //Determine if some validator fails
            value = true;
            for(k=0; k < vals.length;k++)
                value = (value && vals[k].isvalid);
            
            ChangeLabelColor(lbl, value);
            var req = document.getElementById(val.controltovalidate + '_req');
            if (req!=null) {
                ChangeLabelColor(req, value);
            }
        }        
    }
    
    function SetErrorLabelColor(labelName) {
        var lbl = document.getElementById(labelName + '_lbl');
        if (lbl!=null) {
            ChangeLabelColor(lbl, false);
        }
        var req = document.getElementById(labelName + '_req');
        if (req!=null) {
            ChangeLabelColor(req, false);
        }
    }

    function ChangeLabelColor(lbl, valid){
            // Change label text color
            if (valid) {
                lbl.style.color = ''; // no style on label...
                lbl.style.fontWeight = '';
            }else{
                lbl.style.color = 'red'; // error color, red
                //lbl.style.fontWeight = 'bold';
            }    
    }
function phoneOver(elem) {      	
      	if (elem.className!='phoneMenuActive') {
      		elem.style.border = '2px solid #000000';
      		elem.style.padding = '0px';
      	}
      }
      function phoneOut(elem) {
      	if (elem.className!='phoneMenuActive') {
      		elem.style.border = 'none';
      		elem.style.padding = '2px';
      	}
      }
      function setPhoneMenuClass(elem) {
      	var i;
      	if (elem.hasChildNodes()){
      		for(i=0;i<elem.childNodes.length;i++) {
      			if (elem.childNodes[i].className == 'phoneMenuActive') {
      				elem.childNodes[i].className = 'phoneMenu';
      				elem.childNodes[i].style.border = 'none';
      				elem.childNodes[i].style.padding = '2px';
      			}
	      			
      			setPhoneMenuClass(elem.childNodes[i])
      		}
      	}
      }
      function phoneClick(elem) {
      	setPhoneMenuClass(document.getElementById('phoneMenuContainer'));
      	elem.style.border = '2px solid #0099ff';
      	elem.style.padding = '0px';
      	elem.className = 'phoneMenuActive';
      }

/* flipflop function for expanding components*/
function flipflop(tmpElement){
                                            if(tmpElement.getAttribute("status") == "expanded"){
                                                                 $(".flipflop_content",tmpElement.parentNode).slideUp("slow");
                                                                 tmpElement.setAttribute("status","collapsed");
                                                                  $(".flipflop_image",tmpElement.parentNode).attr('src',$(".flipflop_img_off",tmpElement.parentNode).attr('src'));
                                            } else {
                                                                 $(".flipflop_content",tmpElement.parentNode).slideDown("slow");
                                                                 tmpElement.setAttribute("status","expanded");
                                                                 var tmpUrl = $(".flipflop_img_on",tmpElement.parentNode).attr('src');
                                                                 if (tmpUrl!='null') $(".flipflop_image",tmpElement.parentNode).attr('src',$(".flipflop_img_on",tmpElement.parentNode).attr('src'));
                                            }
}

function TelenorChangeBG (elem, bg) {
	elem.tempBG = elem.style.backgroundImage;
	elem.style.backgroundImage = 'url('+bg+')';
}
function TelenorRevertBG (elem) {
	elem.style.backgroundImage = elem.tempBG;
}
function DomWindowInit() {
	Sonofon.Page.Tabs.initialize();
}

(function($){
	
	//closeDOMWindow
	$.fn.closeDOMWindow = function(settings){
		
		if(!settings){settings={};}
		
		var run = function(passingThis){
			
			if(settings.anchoredClassName){
				$('.'+settings.anchoredClassName).fadeOut('fast',function(){
					if($.fn.draggable){
						$('.'+settings.anchoredClassName).draggable('destory').trigger("unload").remove();	
					}else{
						$('.'+settings.anchoredClassName).trigger("unload").remove();
					}
				});
				if(settings.functionCallOnClose){settings.functionCallAfterClose();}
			}else{
				$('#DOMWindowOverlay').fadeOut('fast',function(){
					$('#DOMWindowOverlay').trigger('unload').unbind().remove();																	  
				});
				$('#DOMWindow').fadeOut('fast',function(){
					if($.fn.draggable){
						$('#DOMWindow').draggable("destroy").trigger("unload").remove();
					}else{
						$('#DOMWindow').trigger("unload").remove();
					}
				});
			
				$(window).unbind('scroll.DOMWindow');
				$(window).unbind('resize.DOMWindow');
				
				if($.fn.openDOMWindow.isIE6){$('#DOMWindowIE6FixIframe').remove();}
				if(settings.functionCallOnClose){settings.functionCallAfterClose();}
			}	
		};
		
		if(settings.eventType){//if used with $().
			return this.each(function(index){
				$(this).bind(settings.eventType, function(){
					run(this);
					return false;
				});
			});
		}else{//else called as $.function
			run();
		}
		
	};
	
	//allow for public call, pass settings
	$.closeDOMWindow = function(s){$.fn.closeDOMWindow(s);};
	
	//openDOMWindow
	$.fn.openDOMWindow = function(instanceSettings){	
		
		var shortcut =  $.fn.openDOMWindow;
	
		//default settings combined with callerSettings////////////////////////////////////////////////////////////////////////
		
		shortcut.defaultsSettings = {
			anchoredClassName:'',
			anchoredSelector:'',
			borderColor:'#ccc',
			borderSize:'4',
			draggable:0,
			eventType:null, //click, blur, change, dblclick, error, focus, load, mousedown, mouseout, mouseup etc...
			fixedWindowY:100,
			functionCallOnOpen:null,
			functionCallOnClose:null,
			height:500,
			loader:0,
			loaderHeight:0,
			loaderImagePath:'',
			loaderWidth:0,
			modal:0,
			overlay:1,
			overlayColor:'#000',
			overlayOpacity:'85',
			positionLeft:0,
			positionTop:0,
			positionType:'centered', // centered, anchored, absolute, fixed
			width:500, 
			windowBGColor:'#fff',
			windowBGImage:null, // http path
			windowHTTPType:'get',
			windowPadding:10,
			windowSource:'inline', //inline, ajax, iframe
			windowSourceID:'',
			windowSourceURL:''
		};
		
		var settings = $.extend({}, $.fn.openDOMWindow.defaultsSettings , instanceSettings || {});
		
		//Public functions
		
		shortcut.viewPortHeight = function(){ return self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;};
		shortcut.viewPortWidth = function(){ return self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;};
		shortcut.scrollOffsetHeight = function(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
		shortcut.scrollOffsetWidth = function(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
		shortcut.isIE6 = typeof document.body.style.maxHeight === "undefined";
		
		//Private Functions/////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		var sizeOverlay = function(){
			if(shortcut.isIE6){//if IE 6
				var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
				var overlayViewportWidth = document.documentElement.offsetWidth - 21;
				$('#DOMWindowOverlay').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
			}else{//else Firefox, safari, opera, IE 7+
				$('#DOMWindowOverlay').css({'height':'100%','width':'100%','position':'fixed'});
			}	
		};
		
		var sizeIE6Iframe = function(){
			var overlayViewportHeight = document.documentElement.offsetHeight + document.documentElement.scrollTop - 4;
			var overlayViewportWidth = document.documentElement.offsetWidth - 21;
			$('#DOMWindowIE6FixIframe').css({'height':overlayViewportHeight +'px','width':overlayViewportWidth+'px'});
		};
		
		var centerDOMWindow = function() {
			if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
				$('#DOMWindow').css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($('#DOMWindow').outerWidth())/2));
			}else{
				$('#DOMWindow').css('left',Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($('#DOMWindow').outerWidth())/2));
				$('#DOMWindow').css('top',Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($('#DOMWindow').outerHeight())/2));
			}
		};
		
		var centerLoader = function() {
			if(shortcut.isIE6){//if IE 6
				$('#DOMWindowLoader').css({'left':Math.round(shortcut.viewPortWidth()/2) + shortcut.scrollOffsetWidth() - Math.round(($('#DOMWindowLoader').innerWidth())/2),'position':'absolute'});
				$('#DOMWindowLoader').css({'top':Math.round(shortcut.viewPortHeight()/2) + shortcut.scrollOffsetHeight() - Math.round(($('#DOMWindowLoader').innerHeight())/2),'position':'absolute'});
			}else{
				$('#DOMWindowLoader').css({'left':'50%','top':'50%','position':'fixed'});
			}
			
		};
		
		var fixedDOMWindow = function(){
			$('#DOMWindow').css('left', settings.positionLeft + shortcut.scrollOffsetWidth());
			$('#DOMWindow').css('top', + settings.positionTop + shortcut.scrollOffsetHeight());
		};
		
		var showDOMWindow = function(instance){
			if(arguments[0]){
				$('.'+instance+' #DOMWindowLoader').remove();
				$('.'+instance+' #DOMWindowContent').append('<div id="DOMWindowClose"></div>');
				$('.'+instance+' #DOMWindowContent').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}DomWindowInit();}); //RKL fix
				$('.'+instance+ ' .closeDOMWindow').click(function(){
					$.closeDOMWindow();	
					return false;
				});
				$('#DOMWindowClose').click(function(){$.closeDOMWindow();});
			}else{
				$('#DOMWindowLoader').remove();
				$('#DOMWindow').append('<div id="DOMWindowClose"></div>');
				$('#DOMWindow').fadeIn('fast',function(){if(settings.functionCallOnOpen){settings.functionCallOnOpen();}DomWindowInit();}); //RKL fix
				$('#DOMWindow .closeDOMWindow').click(function(){						
					$.closeDOMWindow();
					return false;
				});
				$('#DOMWindowClose').click(function(){$.closeDOMWindow();});
			}
			centerDOMWindow();
			
		};
		
		var urlQueryToObject = function(s){
			  var query = {};
			  s.replace(/\b([^?&=]*)=([^&=]*)\b/g, function (m, a, d) {
				if (typeof query[a] != 'undefined') {
				  query[a] += ',' + d;
				} else {
				  query[a] = d;
				}
			  });
			  return query;
		};
			
		//Run Routine ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
		var run = function(passingThis){
			
			//get values from element clicked, or assume its passed as an option
			settings.windowSourceID = $(passingThis).attr('href') || settings.windowSourceID;
			settings.windowSourceURL = $(passingThis).attr('href') || settings.windowSourceURL;
			settings.windowBGImage = settings.windowBGImage ? 'background-image:url('+settings.windowBGImage+')' : '';
			var urlOnly, urlQueryObject;
			
			
			if(settings.positionType == 'anchored'){//anchored DOM window
				
				var anchoredPositions = $(settings.anchoredSelector).position();
				var anchoredPositionX = anchoredPositions.left + settings.positionLeft;
				var anchoredPositionY = anchoredPositions.top + settings.positionTop;
				
				$('body').append('<div class="'+settings.anchoredClassName+'" style="'+settings.windowBGImage+';background-repeat:no-repeat;padding:'+settings.windowPadding+'px;overflow:auto;position:absolute;top:'+anchoredPositionY+'px;left:'+anchoredPositionX+'px;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+';z-index:10001"><div id="DOMWindowContent" style="display:none"></div></div>');		
				//loader
				if(settings.loader && settings.loaderImagePath !== ''){
					$('.'+settings.anchoredClassName).append('<div id="DOMWindowLoader" style="width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
					
				}

				if($.fn.draggable){
					if(settings.draggable){$('.' + settings.anchoredClassName).draggable({cursor:'move'});}
				}
				
				switch(settings.windowSource){
					case 'inline'://////////////////////////////// inline //////////////////////////////////////////
						$('.' + settings.anchoredClassName+" #DOMWindowContent").append($(settings.windowSourceID).children());
						$('.' + settings.anchoredClassName).unload(function(){// move elements back when you're finished
$('.' + settings.anchoredClassName+" #DOMWindowContent #DOMWindowClose").remove();
							$('.' + settings.windowSourceID).append( $('.' + settings.anchoredClassName+" #DOMWindowContent").children());				
						});
						showDOMWindow(settings.anchoredClassName);
					break;
					case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
						$('.' + settings.anchoredClassName+" #DOMWindowContent").append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" class="'+settings.anchoredClassName+'Iframe" ></iframe>');
						$('.'+settings.anchoredClassName+'Iframe').load(showDOMWindow(settings.anchoredClassName));
					break;
					case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////	
						if(settings.windowHTTPType == 'post'){
							
							if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
								urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
								urlQueryObject = urlQueryToObject(settings.windowSourceURL);
							}else{
								urlOnly = settings.windowSourceURL;
								urlQueryObject = {};
							}
							$('.' + settings.anchoredClassName+" #DOMWindowContent").load(urlOnly,urlQueryObject,function(){
								showDOMWindow(settings.anchoredClassName);
							});
						}else{
							if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
								settings.windowSourceURL += '?';
							}
							$('.' + settings.anchoredClassName+" #DOMWindowContent").load(
								settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
								showDOMWindow(settings.anchoredClassName);
							});
						}
					break;
				}
				
			}else{//centered, fixed, absolute DOM window
				
				//overlay & modal
				if(settings.overlay){
					$('body').append('<div id="DOMWindowOverlay" style="z-index:10000;display:none;position:absolute;top:0;left:0;background-color:'+settings.overlayColor+';filter:alpha(opacity='+settings.overlayOpacity+');-moz-opacity: 0.'+settings.overlayOpacity+';opacity: 0.'+settings.overlayOpacity+';"></div>');
					if(shortcut.isIE6){//if IE 6
						$('body').append('<iframe id="DOMWindowIE6FixIframe"  src="blank.html"  style="width:100%;height:100%;z-index:9999;position:absolute;top:0;left:0;filter:alpha(opacity=0);"></iframe>');
						sizeIE6Iframe();
					}
					sizeOverlay(); 
					$('#DOMWindowOverlay').fadeIn('fast');
					if(!settings.modal){$('#DOMWindowOverlay').click(function(){$.closeDOMWindow();});}
				}
				
				//loader
				if(settings.loader && settings.loaderImagePath !== ''){
					$('body').append('<div id="DOMWindowLoader" style="z-index:10002;width:'+settings.loaderWidth+'px;height:'+settings.loaderHeight+'px;"><img src="'+settings.loaderImagePath+'" /></div>');
					centerLoader();
				}

				//add DOMwindow
				$('body').append('<div id="DOMWindow" style="background-repeat:no-repeat;'+settings.windowBGImage+';overflow:auto;padding:'+settings.windowPadding+'px;display:none;height:'+settings.height+'px;width:'+settings.width+'px;background-color:'+settings.windowBGColor+';border:'+settings.borderSize+'px solid '+settings.borderColor+'; position:absolute;z-index:10001"></div>');
				
				//centered, absolute, or fixed
				switch(settings.positionType){
					case 'centered':
						centerDOMWindow();
						if(settings.height + 50 > shortcut.viewPortHeight()){//added 50 to be safe
							$('#DOMWindow').css('top', (settings.fixedWindowY + shortcut.scrollOffsetHeight()) + 'px');
						}
					break;
					case 'absolute':
						$('#DOMWindow').css({'top':(settings.positionTop+shortcut.scrollOffsetHeight())+'px','left':(settings.positionLeft+shortcut.scrollOffsetWidth())+'px'});
						if($.fn.draggable){
							if(settings.draggable){$('#DOMWindow').draggable({cursor:'move'});}
						}
					break;
					case 'fixed':
						fixedDOMWindow();
					break;
				}
				
				$(window).bind('scroll.DOMWindow',function(){
					if(settings.overlay){sizeOverlay();}
					if(shortcut.isIE6){sizeIE6Iframe();}
					if(settings.positionType == 'centered'){centerDOMWindow();}
					if(settings.positionType == 'fixed'){fixedDOMWindow();}
				});

				$(window).bind('resize.DOMWindow',function(){
					if(shortcut.isIE6){sizeIE6Iframe();}
					if(settings.overlay){sizeOverlay();}
					if(settings.positionType == 'centered'){centerDOMWindow();}
				});
				
				switch(settings.windowSource){
					case 'inline'://////////////////////////////// inline //////////////////////////////////////////
						$("#DOMWindow").append($(settings.windowSourceID).children());
						$("#DOMWindow").unload(function(){// move elements back when you're finished
							$("#DOMWindow #DOMWindowClose").remove();
							$(settings.windowSourceID).append( $("#DOMWindow").children());				
						});
						showDOMWindow();
					break;
					case 'iframe'://////////////////////////////// iframe //////////////////////////////////////////
						$('#DOMWindow').append('<iframe frameborder="0" hspace="0" wspace="0" src="'+settings.windowSourceURL+'" name="DOMWindowIframe'+Math.round(Math.random()*1000)+'" style="width:100%;height:100%;border:none;background-color:#fff;" id="DOMWindowIframe" ></iframe>');
						$('#DOMWindowIframe').load(showDOMWindow());
					break;
					case 'ajax'://////////////////////////////// ajax //////////////////////////////////////////
						if(settings.windowHTTPType == 'post'){
							
							if(settings.windowSourceURL.indexOf("?") !== -1){//has a query string
								urlOnly = settings.windowSourceURL.substr(0, settings.windowSourceURL.indexOf("?"));
								urlQueryObject = urlQueryToObject(settings.windowSourceURL);
							}else{
								urlOnly = settings.windowSourceURL;
								urlQueryObject = {};
							}
							$("#DOMWindow").load(urlOnly,urlQueryObject,function(){
								showDOMWindow();
							});
						}else{
							if(settings.windowSourceURL.indexOf("?") == -1){ //no query string, so add one
								settings.windowSourceURL += '?';
							}
							$("#DOMWindow").load(
								settings.windowSourceURL + '&random=' + (new Date().getTime()),function(){
								showDOMWindow();
							});
						}
					break;
				}
				
			}//end if anchored, or absolute, fixed, centered
			
		};//end run()
		
		if(settings.eventType){//if used with $().
			return this.each(function(index){				  
				$(this).bind(settings.eventType,function(){
					run(this);
					return false;
				});
			});	
		}else{//else called as $.function
			run();
		}
		
	};//end function openDOMWindow
	
	//allow for public call, pass settings
	$.openDOMWindow = function(s){$.fn.openDOMWindow(s);};
	
})(jQuery);

$(document).ready(function (){

$('.smallLightbox').openDOMWindow({ height:500, width:300, positionType:'centered', eventType:'click', windowSource:'ajax', windowHTTPType:'post', borderSize:0,windowPadding:0,loaderImagePath:'/Images/ajax_loader_tcm52-84335.gif',loaderHeight: 31, loaderWidth:31,loader:1  }); 
$('.mediumLightbox').openDOMWindow({ height:500, width:788, positionType:'centered', eventType:'click', windowSource:'ajax', windowHTTPType:'post', borderSize:0,loaderImagePath:'/Images/ajax_loader_tcm52-84335.gif',loaderHeight: 31, loaderWidth:31,loader:1  }); 
$('.largeLightbox').openDOMWindow({ height:800, width:800, positionType:'centered', eventType:'click', windowSource:'ajax', windowHTTPType:'post', borderSize:0,loaderImagePath:'/Images/ajax_loader_tcm52-84335.gif',loaderHeight: 31, loaderWidth:31,loader:1  }); 

$('.popup').openDOMWindow({ height:400, width:527, positionType:'centered', eventType:'click', windowSource:'ajax', windowHTTPType:'post', borderSize:0,windowPadding:10,loaderImagePath:'/Images/ajax_loader_tcm52-84335.gif',loaderHeight: 31, loaderWidth:31,loader:1  }); 
$('.popup_inline').openDOMWindow({ height:300, width:400, positionType:'centered', eventType:'click', borderSize:0,windowPadding:10,loaderImagePath:'/Images/ajax_loader_tcm52-84335.gif',loaderHeight: 31, loaderWidth:31,loader:1  }); 


});

