/**
*	javascript.js
*	
*   This is the default javascript functions of CoreTreks Site Base for CorePublish frontends
*	
*	Please DO NOT CHANGE this file. 
*	To add your own functions, put them in another file
*	This makes sure you can update this file (javascript.js)
*	from a newer distribution without worrying about keeping your changes.
*
*	@author Arve Skjørestad
*	
*/

var timervar = null; 

function printArticle( artUrl ){
    behind = window.open(artUrl ,'printwin','height=620,width=620,status=yes,toolbar=yes,directories=no,menubar=yes,location=no,resizable=yes,scrollbars=yes');
    behind.focus();
}


function getContentAreaHeight() {
    if (document.all) {
        var ret  =  document.all["menuheighholder"].height;
    } else if (document.getElementById) {
		var ret =  document.getElementById("menuheighholder").height;
    }

    return  ret;

}       

function getAbsolutePos(el){
	for (var lx=0,ly=0;el!=null;
		lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
	return {x:lx,y:ly}
}


/**
 * Sets the active stylesheet for the page.
 * 
 * 
 */
function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
       if(a.getAttribute("rel").indexOf("style") != -1
          && a.getAttribute("title")) {
           a.disabled = true;
           if(a.getAttribute("title") == title) {
               a.disabled = false;
           }
       }
   }
}

function getActiveStyleSheet() {
    var i, a;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
        if(a.getAttribute("rel").indexOf("style") != -1
           && a.getAttribute("title")
           && !a.disabled) { 
            return a.getAttribute("title");
        }
    }
    return null;
}

var debugwin;
var debugwinopened = false;
function debug(str) {
    //return;
    // alert(str); return ;
	if (debugwinopened == false || !debugwin) {
        debugwin = window.open('about:blank','debug_window','width=1000,height=700, toolbars=no,menu=no,scrollbars=yes');
        debugwin.document.write("<h3>CorePublish Javascript Debug</h3>");
        debugwinopened = true;
    }
	debugwin.document.write( str );
	debugwin.focus();
    // make the debug win go away after a while..
    setTimeout("self.focus()",2000);
	// alert(str);
}

/**
*   Function displays the metods and properties of an javascript object
*   @param Object inarray - The array to serialize.
*/
function jsdebug(inarray, level) {
    var result = '';
    var sep = '';

    if (level > 5) {
        return;
    }

    if(inarray!=null) {
        for(var key in inarray) {
            
            if (inarray[key] == null) {
                continue;
            }

            result = "<ul>" +  typeof inarray[key];
            result += ' [' + key + '] => ';

            try {
                tmp = inarray[key].toString();
                result += tmp.substring(0,90) + "";
            } catch (e) {
                result += tmp + "";
            } 

            debug(result);
                
            if (typeof inarray[key] == "object" || typeof inarray[key] == "function") {
                jsdebug(inarray[key],level+1);
            }

            debug("</ul>");
            /*
            if(typeof inarray[key] == 'object') {
                result += '[object]';
            } else {
                result += inarray[key].toString();
            }     */



            /*if (result.length > 1000) {
                alert(result + " (continues >>) ");
                result = "";
            } */

        } 
    } else {
        result = "[null]";
    }
    // alert(result);
}

document.observe('dom:loaded', function(event) {

	// Toggling the product categories in the order form
	$$('a.toggler').each(function(element) {
	    element.observe('click', function(event) {
	        Event.stop(event);
	        
	        var elementID = Event.element(event).id;
	        var ID = elementID.replace("productlist-category-", "");
	        
	        $("productlist-items-"+ID).toggle();
	    });
	});
	
	// Toggling the grouped searchresult
	$$('a.search-toggler').each(function(element) {
	    element.observe('click', function(event) {
	        Event.stop(event);
	        
	        var observeElementID = Event.element(event).id;

	        var commonElementID = observeElementID.replace("search-groupedresult-link-", "");
	        
	        toggleElementID = "search-groupedresult-"+commonElementID;
	        
	        //hide all open elements before toggling
			$$('div.search-groupedresult').each(function(element) {
	        	element.hide();
	        });
			
			//remove class name of all header links
	        $$('a.search-toggler').each(function(element) {
	        	element.removeClassName('open');
	        });
			
			//toggle correct element
			if($(toggleElementID) != null) {
				$(toggleElementID).show();
				//add a css-classname for open divs, used for styling
				$(observeElementID).addClassName('open');
			}
	        
	    });
	});
	
	
	// Adding up all product lines in the prognosis form
	$$('input.productAmount').each(function(element) {
        
		element.observe('change', function(event) {
			var matches = element.id.split(/-/);
			
			var sum = $$('input.productAmount-'+matches[1]).inject(0, function(acc, element) {
				if (element.value == '') {
					var amount = 0;
				} else {
					var amount = parseInt(element.value);
				}
				return parseInt(acc) + amount;
			});
			
			if (isNaN(sum)) {
				$('totalProductAmount-'+matches[1]).update('');
			} else {
				$('totalProductAmount-'+matches[1]).update(sum);
			}
			
			
		});
	});

});

function secundsCalc(secunds, num1, num2) {
	s = ((Math.floor(secunds/num1))%num2).toString();
	
	return (s);
}

/**
*	Class used in the tile linktoolbar
*	Take care for toggling sharing container and submit form with ajax
*/
var NorturaToolbarSuggestionTile = Class.create({
	
	initialize: function(element,successMessage,failureMessage) {
		
		this.element = $(element);
		this.form = this.element.select('form').first();
		
		this.formMessageElement = $('toolbar-suggestion-form-message');
		
		this.successMessage = successMessage;
		this.failureMessage = failureMessage;
		
		$$('a.sharing_link','a.close-link').each(function(element) {
			element.observe('click',function(event) {
				Effect.toggle('sharing','blind', { duration: 0.7 });
			});
		});
		
		this.form.observe('submit', this.formSubmitListener.bindAsEventListener(this));
	},
	
	// supports errortype success and failure
	setResponseMessage: function(errorType) {
		// Set response text as error message
		
		classNameRemove = "";
		classNameAdd = "";
		responseMessage = "";
		
		if(errorType == "success") {
			classNameRemove = "form-failure";
			classNameAdd = "form-success";
			responseMessage = this.successMessage;
		}
		else if(errorType == "failure") {
			classNameRemove = "form-success";
			classNameAdd = "form-failure";
			responseMessage = this.failureMessage;
		}
		
        this.formMessageElement.innerHTML = '';
    	this.formMessageElement.innerHTML = responseMessage;
    	this.formMessageElement.removeClassName(classNameRemove);
    	this.formMessageElement.addClassName(classNameAdd);
    	
	},
	
	formSubmitListener: function(event) {
	
		// Stop the original submit
        event.stop();
        
        var form = event.element();
        
        // Removes any element-error classes from the DOM
        // below this element
        form.select('div.input-label').each(function(element) {
        	element.removeClassName('element-error');
        });
            
		// Do an Ajax post to the forms action using the defined method
        new Ajax.Request(form.readAttribute('action'), {
            method: form.readAttribute('method'),
            parameters: form.serialize(),
            
            onSuccess: function(res) {
                // If form was submitted, we output the form saved message
                // from the form handler
                //alert(res.responseText.evalJSON());
                
		        this.setResponseMessage('success');
		        Effect.toggle('sharing','blind', { duration: 0.7, delay: 3.0 });
            }.bind(this),
            
            onFailure: function(res) {
                var status = res.responseText.evalJSON();
                
                var errorMessagePrinted = false;
                
                for(id in status) {
                    // id contains the element name that has an error, lets
                    // get the actual element from DOM

                    if(errorMessagePrinted == false) {
			        	errorMessagePrinted = true;
			        	this.setResponseMessage('failure');
			        }
			        
                    var errorElement = $(id);
                    var errorLabelElement = $('input-label-'+id);
                    
                    // Add extra css class to label for error element, used to set red color in css
                    errorLabelElement.addClassName('element-error');
                    
                    // Lets pulase the element that did not validate, just
                    // to draw user attention
                    new Effect.Pulsate(errorLabelElement, { pulses: 2, duration: 1.0 });
                }
                
            }.bind(this)
        });
		
	}
	
});

//Class used to create a random css-class for an given element. css-class is a random value from an array
NorturaSetRandomTheme = Class.create({
	
	//which element to changed css-class on
	element : "",
	//array with possible themes
	themeArray : "",
	
	initialize : function(elementID,themeArray){
		this.element = $(elementID);
		this.themeArray = themeArray;
		
		this.setCssClass();
	},
	//function that add a random theme as css name on specified element
	setCssClass : function() {
		
		//get a random value from theme array
		var arrayLength = this.themeArray.length;
		
		if(arrayLength <= 0) {
			return;
		}
		
		randomArrayIndex = Math.floor(Math.random()*(arrayLength));
		
		//set css-class to a random array value
		themeCssClass = "";
		themeCssClass = this.themeArray[randomArrayIndex];
		if(themeCssClass.length > 0) {
			this.element.addClassName(themeCssClass);
		}
	}
	
});


NorturaTimeCounter = Class.create({

	//divelement
	element : "",
	offerelement : "",
	//numbers of seconds to count
	secundsCountDown : "", 
	secundsCountUp : "", 
	/*PeriodicalExecuter*/                   
	pe : null,
	//flag set after countdown finishes
	finished : false, 
	
	//wether to count down or up
	countDown : true, 
	
	displayString : "",
	displayFormat : "%%D%% dager, %%H%% timer %%M%% min %%S%% sek",          
	
	initialize : function(secundsCountDown,secundsCountUp,element,offerElement,countDown){
		this.secundsCountDown = secundsCountDown;
		this.secundsCountUp = secundsCountUp;
		this.element = element;
		this.offerelement = offerElement;
		this.countDown = countDown;
		this.pe = new PeriodicalExecuter(this.execute.bind(this),1);
		window.onload = this.abort.bindAsEventListener(this);
	},
	
	abort : function(evt){
		/*$(this.element).innerHTML = "abort";
		//window.onblur = '';
		window.onfocus = this.resume.bindAsEventListener(this);
		this.pe.stop();*/
	},
	
	resume : function(evt){  
		if(this.finished){
			window.onfocus = '';
			window.onload = ''; 
		}
		else{
			this.pe = new PeriodicalExecuter(this.execute.bind(this),1);
			window.onfocus = '';
			window.onload = this.abort.bindAsEventListener(this);    
		}
	
	},
	
	restart : function(){
		this.pe.stop();
		this.pe = new PeriodicalExecuter(this.execute.bind(this),1);
		window.onload = this.abort.bindAsEventListener(this);  
	},
	
	execute : function(_pe){
		
		if(this.countDown) {
			this.displayString = this.displayFormat.replace(/%%D%%/g,		secundsCalc(this.secundsCountDown,86400,100000));
			this.displayString = this.displayString.replace(/%%H%%/g,		secundsCalc(this.secundsCountDown,3600,24));
			this.displayString = this.displayString.replace(/%%M%%/g,		secundsCalc(this.secundsCountDown,60,60));
			this.displayString = this.displayString.replace(/%%S%%/g,		secundsCalc(this.secundsCountDown,1,60));
			
			$(this.element).innerHTML = this.displayString;
		
			if(this.secundsCountDown <= 0){
				this.pe.stop();
				
				$(this.element).innerHTML = "Ferdig"
				new Effect.BlindUp($(this.offerelement));
				window.onload = '';
				window.onhelp = ''; 
			}
		
			this.secundsCountDown--;
		}
		else {
			this.secundsCountUp++;
			if(this.secundsCountUp == 0) {
				this.pe.stop();
				
				new Effect.BlindDown($(this.offerelement));
				NorturaStartDownCounter(this.secundsCountDown);
				window.onload = '';
				window.onhelp = ''; 
			}
		}
		
	} 
});

function NorturaStartDownCounter(secundsCount) {
	norturaTimeCounter = new NorturaTimeCounter(secundsCount,0,'timecounter','offerinputdiv',true);
}


function NorturaRedirectToSelected(selector, stayInSameWindow) {
    if(selector!=null) {
        var selindex = selector.selectedIndex;
        var chosenoption = selector.options[selindex];
        if(chosenoption!=null && chosenoption.value!="") {
        
            if (stayInSameWindow != null && stayInSameWindow == true ) {
                location.href = chosenoption.value; 
            } else  {
                window.open(chosenoption.value);
                selector.selectedIndex=0;
            }
        }
    }
}

// Callback function when image loading failed...
function NorturaReplaceBrokenImage(imageurl,newImage) {
    if(imageurl!=null) {
        imageurl.src = newImage;
    }
}
function clearInput(object, string) {
	if(object.value == string) {
 		object.value = '';
 	}
}

function checkAll(checkname, exby) {
	for (i = 0; i < checkname.length; i++) {
		checkname[i].checked = exby? true:false;
	}
}