/**
    (#) file: Util.js

    IDG related javascript utility class
*/

function launchPopup(url, name, width, height, resizable, scrollbars, toolbar, location) {
  popup_window = window.open(url, name, 'width='+width+',height='+height+',resizable='+resizable+',scrollbars='+scrollbars+',toolbar='+toolbar+',location='+location+'');
  popup_window.focus();
}
var Util = {

        getXmlDoc:function(xmlString) {
            var myDocument;
            if (document.implementation.createDocument)
            {
                var parser = new DOMParser();
                myDocument = parser.parseFromString(xmlString, "text/xml");
            }
            else if (window.ActiveXObject)
            {
                myDocument = new ActiveXObject("Microsoft.XMLDOM");
                myDocument.async = "false";
                myDocument.loadXML(xmlString);
            }
            return myDocument;
        },
        verifyAdContent: function(element) {
            try {
                element = $(element);
                var beforeHtml = element.innerHTML;
                var selfHtml = "Util.verifyAdContent";
                var invalidHtml = beforeHtml.indexOf( selfHtml ) != -1;

                if( invalidHtml ) {
                    document.write("</div>");
                }
            }
            catch( e ) {
                alert(e);
            }
        },
        checkAnonym: function( form, params ) {
            var dummy_text_field = $('forfatter_text_field_dummy');

            if(dummy_text_field != null){
                var name = $('forfatter_text_field');
                name.value = dummy_text_field.value;

                if( name.value == null || name.value == "") {
                    name.value = "Anonym";
                }
            }

            var dummy_email_field = $('email_text_field_dummy');

            if(dummy_email_field != null){
                var email = $('email_text_field');
                email.value = dummy_email_field.value;

                if( email.value == null || email.value == "" ) {
                    email.value = "Anonym@epost";
                }
            }

            return Validate.form( form, params );
        },
        /* display window lock UI */
        setWindowLock: function(b) {
            if(b == true) {
                this._showLockWindow();
            }
            else {
                this._releaseLockWindow();
            }
        },

        _getLockWindow: function() {

            var nDiv = null;
            if($('lock-window') == null) {
                nDiv = document.createElement("div");
                nDiv.id="lock-window";
                nDiv.zindex=100;
                nDiv.innerHTML = "<div id='lock-window-header'>Laster...</div>";

                var body = document.getElementsByTagName("body")[0];
                body.appendChild(nDiv);
            }
            else {
                nDiv = $('lock-window');
            }

            return nDiv;
        },
        _showLockWindow: function() {
            this._getLockWindow().style.display="none";
            new Effect.ScrollTo('lock-window',{queue: 'front'});
            Effect.Appear(this._getLockWindow(),{queue: 'end'});
        }
        ,_releaseLockWindow: function() {
            Effect.Fade(this._getLockWindow());
            new Effect.ScrollTo('imagePages',{queue: 'end'});
        },

        /**
            Specify divId, tagName and cssClass
        */
        setCssClass: function(params) {
            try {
                var div=$(params.divId);
                var elements=div.getElementsByTagName(params.tagName);

                // reset all same element calss
                for(var i=0; i<elements.length; i++) {
                    var element=elements[i];
                    if(element.className == params.cssClass)
                        element.className="";
                }

                // set this element class
                params.setTo.className=params.cssClass;
            }
            catch(e) {
                alert(e);
            }
        },

        sendRedirect: function(link) {

        },

        /**
            Show "Loading..." text
        */
        startLoading: function(divId) {
            $(divId).style.display="block";
            $(divId).innerHTML="<b>Laster...</b>";
        },
        endLoading: function(divId) {
            $(divId).style.display="none";    
        },

        /**
            Open new window
        */
        newWindow: function(url, options) {
            var nWin=window.open(url,"_blank",options);
        },

        /*
            Load content
        */
        loadContent: function(url) {

        },

        /**
            Load AjAx based content
        */
        loadAjaxContent: function(request) {
            try {
                var xmlDoc=Util.getXmlDoc(request.responseText);
                // retrieve 'action'
                var actions = xmlDoc.getElementsByTagName("action");

                // retrieve all action
                for(var i=0; i<actions.length; i++) {
                    // handle tag
                    switch(actions[i].tagName) {
                        case "action":
                            var divId = null;
                            var type = null;
                            var value = null;

                            for (var j=0; j < actions[i].childNodes.length; j++) {
                                var child=actions[i].childNodes[j];
                                switch (child.nodeName) {
                                    case "divId":
                                        divId=child.firstChild.data;
                                        type=child.getAttribute("type");
                                        break;
                                    case "value":
                                        value=child.firstChild.data;
                                        var tagName = $(divId).tagName.toUpperCase();
                                        // set value to certain divId
                                        switch (tagName) {
                                            case "IMG":
                                                var img = new Image();
                                                img.src=value;
                                                $(divId).src=value;
                                                break;
                                            case "DIV":
                                                $(divId).innerHTML=value;
                                                break;
                                            case "H2":
                                                $(divId).innerHTML=value;
                                                break;
                                            case "P":
                                                $(divId).innerHTML=value;
                                            default:
                                                $(divId).innerHTML = value;
                                                break;
                                        }
                                        break;
                                    case "effect":
                                        eval(child.firstChild.data);
                                        break;
                                }
                            }
                            break;
                    }
                }

            }
            catch(e) {
                alert(e.message);
            }

        }
}

/**
    SlideShow controller
*/
var SlideShow = {

    currentLink: 0,
    maxLinks: 0,
    urlPrefix: "___link__",

    showNext: function(params) {
        var url=params.url+"&current="+
                this.getNewCursor(params.max, params.updateCursor);

        document.body.style.cursor="wait";
        new Ajax.Updater('',url, {onComplete: function(request) {
                    Util.loadAjaxContent(request);
                    document.body.style.cursor="default";
                }});
    },
    getNewCursor: function(max, uc) {
        // retrieve current cursor
        var cc=Number($(uc).innerHTML);
        max=Number(max);
        // create new cursor
        if(max > cc) {
            cc +=1;
            $(uc).innerHTML=cc;
        }
        // else do nothing...
        return cc;
    },
    showPrev: function(params) {
        var url=params.url+"&current="+
                this.getPrevCursor(params.max, params.updateCursor);

        document.body.style.cursor="wait";
        new Ajax.Updater('',url, {onComplete: function(request) {
                    Util.loadAjaxContent(request);
                    document.body.style.cursor="default";
                }});
    },
    getPrevCursor: function(max, uc) {
        // retrieve current cursor
        var cc=Number($(uc).innerHTML);
        max=Number(max);
        // create new cursor
        if (cc <= max && cc > -1) {
            cc -=1;
            $(uc).innerHTML=cc;
        }
        // else do nothing...

        return cc;
    },
    setCurrentLink: function(c) {
        this.currentLink = c;
    },
    nextLink: function() {
        try {
            this.currentLink = this.currentLink + 1;
            if (this.currentLink > this.maxLinks)
                this.currentLink = this.maxLinks;
            var aLink = $(this.urlPrefix + this.currentLink);
            if (aLink !=null)
                if (aLink.onclick !=null)
                    aLink.onclick.call(aLink);
            else {
                this.maxLinks = this.currentLink-1;
                this.currentLink = this.maxLinks;
            }
        }
        catch (e) {
            alert( e );
        }
    },
    prevLink: function() {
        try {
            this.currentLink = this.currentLink - 1;
            if (this.currentLink < 1)
                this.currentLink = 1;
            var aLink = $(this.urlPrefix+this.currentLink);
            if (aLink !=null) {
                if (aLink.onclick !=null)
                    aLink.onclick.call( aLink );
            }
            else
                this.currentLink = this.maxLinks;
        }
        catch(e) {
            alert(e);
        }
    }
}

/*
    JavaScript validation class
*/
var Validate={

    formInputFields: null,
    formTextArea: null,
    formSelect: null,

    // set notEmpty as parameter to perform not empty validation
	// set equalTo as parameter to compare 2 fileds validation...
	// you have to setup update parameter so... it will setup the error message
	form: function(form, params) {

		var msg="";

		// validate "notEmpty"
		for(var i=0; i<params.notEmpty.length; i++) {
			var field=params.notEmpty[i];
            var iField=this.getField(form, field);
            if(this.isEmpty(iField)) {
				msg +="<li><b>"+field+"</b> is empty</li>\r\n";
				this.errorHighlight(iField);

			}
			else {
				this.removeHighlight(field);
			}
		}

		// validate "equalTo"
        if(params.equalTo !=null ) {
            for(var i=0; i<params.equalTo.length; i++) {
                var fields=params.equalTo[i];

                var field1 = fields.substring(0,fields.indexOf(","));
                var field2 = fields.substring(fields.indexOf(",")+1,fields.length);

                if(this.getField(form, field1).value !=this.getField(form, field2).value) {
                    this.errorHighlight(field1);
                    this.errorHighlight(field2);
                    msg +="<li>"+field1+" does not equal to "+field2+"</li>";
                }
            }
        }


        // set message
		if(msg !="") {
            if(params.update !=null) {
                document.getElementById(params.update).innerHTML="<ul>"+msg+"</ul>";
                document.getElementById(params.update).style.textAlign="left";

                // show effect
                new Effect.ScrollTo(params.update,{duration:2.0});
            }

            // stop form submitting
            return false;
		}

		return true;
	},
	isEmpty: function(field) {
		if(field !=null && field.value !=null && field.value.length>0) {
            return false;
		}
        else {
			return true;
        }
    },
	removeHighlight: function(field) {
		var fObj=document.getElementsByName(field).item(0);

		if(fObj !=null) {
			fObj.style.border="1px";
			fObj.style.borderColor="#0066cc";
			fObj.style.borderStyle="solid";
		}
	},
	errorHighlight: function(field) {
		var fObj=field;

        if(fObj !=null) {
			fObj.style.border="5px";
			fObj.style.borderColor="red";
			fObj.style.borderStyle="solid";
		}

//        Effect.Shake(fObj)
    },

	getField: function(form, fieldName) {

        var iField=document.getElementsByName(fieldName);
        if(iField.length > 0)
            return iField[0];

        if($(fieldName) !=null) {
            return $(fieldName);
        }

        if(this.formInputFields == null) {
            formInputFields = form.getElementsByTagName("input");
            formTextArea = form.getElementsByTagName("textarea");
            formSelect=form.getElementsByTagName("select");
        }

        // retrieve inputfield
        for(var i=0; i<formInputFields.length; i++) {
            if(formInputFields.item(i).name==fieldName) {
				return formInputFields.item(i);
			}
		}
        // retrieve textarea
        for(var i=0; i<formTextArea.length; i++) {
            if(formTextArea.item(i).name==fieldName) {
				return formTextArea.item(i);
			}
		}
        // retrieve select field
        for(var i=0; i<formSelect.length; i++) {
            if(formSelect.item(i).name==fieldName) {
				return formSelect.item(i);
			}
		}

        return null;
    }
};


/*********************************************************************/
/* Setter lik høyde på div-tagger med samme ID */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function setTall(searchClass,node,tag) {

	if (document.getElementById) {
		// the divs array contains references to each column's div element.  
		// Replace 'center' 'right' and 'left' with your own.  
		// Or remove the last one entirely if you've got 2 columns.  Or add another if you've got 4!
		
		var divs = new getElementsByClass(searchClass,node,tag);

		// Let's determine the maximum height out of all columns specified
		var maxHeight = 0;
		for (var i = 0; i < divs.length; i++) {
			if (divs[i].offsetHeight > maxHeight) maxHeight = divs[i].offsetHeight;
		}

		// Let's set all columns to that maximum height
		
		for (var i = 0; i < divs.length; i++) {
			divs[i].style.height = maxHeight + 'px';

			// Now, if the browser's in standards-compliant mode, the height property
			// sets the height excluding padding, so we figure the padding out by subtracting the
			// old maxHeight from the new offsetHeight, and compensate!  So it works in Safari AND in IE 5.x
			if (divs[i].offsetHeight > maxHeight) {
				divs[i].style.height = (maxHeight - (divs[i].offsetHeight - maxHeight)) + 'px';
			}
		}
	}
}

window.onload = function() {
	setTall('equalheight', document, '*');
}

window.onresize = function() {
	setTall('equalheight', document, '*');
}
/*********************************************************************/


// url - AJAX URL (page to fetch)
// id - div id to place result in
function fetchPage(url,id) {
                            
    if (service_fetched[id]) {
       return; // already fetched
    }
    new Ajax.Request(url,
    {
      method:'get',
      onSuccess: function(transport){
        var response = transport.responseText || "no response text";
	$(id).update(response);
	service_fetched[id] = 1;
	
      },
      onFailure: function() {$(innerId).update("Error fetching content"); }
    });
  }



function changeCss(theClass,element,value) {
	 var rules;
	 if (document.all) {
	  rules = 'rules';
	 }
	 else if (document.getElementById) {
	  rules = 'cssRules';
	 }
	 for (var sheet = 0; sheet < document.styleSheets.length; sheet++){
	  for (var rule = 0; rule < document.styleSheets[sheet][rules].length; rule++) {
	   if (document.styleSheets[sheet][rules][rule].selectorText == theClass) {
	    document.styleSheets[sheet][rules][rule].style[element] = value;
	   }
	  }
	 }	
	}


  function showMorePrices() {
     $('kelkooLongerList').hide(); 
     //changeCss('.hideRow','display','table-row'); 
     Effect.SlideDown('hiddenTable');
     return false;
  }

