/*
    SiteComponents version:
    6.8.0.1, tag SC_6_8_0_1, created Fri Aug 20 11:18:33 +0200 2010

    Disclaimer
    
    While we make every effort to ensure that this code is fit for its intended
    purpose, we make no guarantees as to its functionality. CoreTrek AS will
    accept no responsibility for the loss of data or any other damage or
    financial loss caused by use of this code.


    Copyright
    
    This programming code is copyright of CoreTrek AS. Permission to run this
    code is given to approved users of CoreTrek's publishing system CorePublish.
    
    This source code may not be copied, modified or otherwise repurposed for use
    by a third party without the written permission of CoreTrek AS.
    
    Contact webmaster@coretrek.com for information.
    
*/

/**
 * Configuration for site components javascript
 *
 * Configuration array structure:
 * {<component>: {<parameter>: value, <parameter>: value, ... }, ...}
 */
var siteComponentsConfig = {
    
    // Configuration for the keyword module.
    
    keywords: {
        elements: ['placeholder-content'],
        skiptags: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
        usetooltip: true
    }
    // Remember to add a comma above when enabling more options
    
    /*
    // Valid keys:
    //    disable: true/false (default enabled)
    //    collapsedPageInfoPosition: Use this to move the collapsed debug
    //                               position to the left, instead of the
    //                               default right.
    debug: {
        disable: true,
        collapsedPageInfoPosition: 'right'
    }
    */
    
    /*
    // Configuration for tooltop.
    // 
    // Valid keys:
    //    disable: true/false (default enabled)
    //    positionby: Use this to override the default position for tooltip.
    //                Valid values is:
    //                  mouse (default), tooltip follows mouse
    //                  element, tooltip is attached to the title element
    tooltip: {
        disable: false,
        positionby: 'mouse'
    }
    */
    
    /*
    // Use this to override the default fontsizes in the fontsize selector
    // (html/lib/fontsize.js)
    
    fontsize: {
        sizes: ["10pt", "15pt", "24pt"]
    }
    */
    
};

/*
Author
--------------------------
Simen Lysebo, August 2009

*/

RoundedCorners = Class.create({

    intervalID: false,
    isIE6: null,

    /*
     * constructor
     * class must be instantiated after dom:loaded
     * takes no action if browser is msie6
     */
    initialize: function() {
        if (Prototype.Browser.IE && navigator.appVersion.match(/MSIE 6\.0/)) {
            this.isIE6 = true;
        }else {
            this.isIE6 = false;
            this.setUpInterval();
        }

    },

    /*
     * img class="rounded" must be checked periodically when page has been loaded
     * as ie7/ie8 sometimes loads images slowly. The interval is stopped when
     * all rounded-images are processed
     */
    setUpInterval: function() {
        if (this.intervalID == false) {
            this.intervalID = setInterval("roundedCorners.iterateImages()", 200);
        } else {
            // interval is already running, taking care of things
        }
    },


    /*
     * Loops through all img.rounded and applies stuff when element boundaries are set up.
     * Removes the rounded class for each finished element, and stops interval when all
     * element are processed
     * */
    iterateImages: function(){
        $$('.rounded').each(function(img){
            overflow++;
            if (img.getWidth() > 0 && img.getHeight() > 0) {
                this.doStuff(img,'');
                img.removeClassName("rounded");
            }
            if (overflow > 10000) {
                img.removeClassName("rounded");
            }
        }.bind(this));

        $$('.rounded_gray').each(function(img){
            overflow++;
            if (img.getWidth() > 0 && img.getHeight() > 0) {
                this.doStuff(img, '_gray');
                img.removeClassName("rounded_gray");
            }
            if (overflow > 10000) {
                img.removeClassName("rounded_gray");
            }
        }.bind(this));

        if (this.intervalID != false) {
            if ($$('.rounded').length == 0 && $$('.rounded_gray').length == 0 ){
                // stop timeout when no more elements can be processed
                clearTimeout(this.intervalID);
                this.intervalID = false;
            }
        }
    },

    /*
     * apply rounded corners. see rounded2 related classes in css
     */
    doStuff: function(img, suffix) {
        // wrap element
        wrapper = img.wrap('div', {'class' : 'rounded_wrapper'});
        // needs to explicitly set class name, because ie8 doesn't
        wrapper.addClassName("rounded_wrapper");
        // add one div for each corner
        img.insert({'before': '<div class="rounded_wrap topleft'+suffix+'"></div>'});
        img.insert({'before': '<div class="rounded_wrap topright'+suffix+'"></div>'});
        img.insert({'before': '<div class="rounded_wrap bottomleft'+suffix+'"></div>'});
        img.insert({'before': '<div class="rounded_wrap bottomright'+suffix+'"></div>'});

        // get dimensions for element
        var w = img.getWidth();
        var h = img.getHeight();

        // set w+h on wrapper, and inherit float from container
        wrapper.setStyle({
            width: w + "px",
            height: h + "px",
            cssFloat: wrapper.up().getStyle("float")
        });

        // set w+h on corner divs
        wrapper.select('div.rounded_wrap').each(function(corner){
            corner.setStyle({
                width: w + "px",
                height: h + "px"
            });
        }.bind(this));

    }

});

var roundedCorners;
var overflow = 0;

document.observe('dom:loaded', function(event){
    roundedCorners = new RoundedCorners();
});




/* Campaign switcher frontpage */

var currentCampaign = 0;
var campaignTimer = 0;

function campaignChangeTo(i) {

    $$('.campaign-articlelist .list-navigation .pages').each(function(link){
        link.down().src = '/themes/commaxx/images/bullet-inactive.png';
    }.bind(this));

    $$('.campaign-articlelist li').each(function(campaign){
        if (campaign.id == 'campaign-item'+i) {
            $('campaignLink'+i).down().src = '/themes/commaxx/images/bullet-active.png';
            campaign.appear({duration: 1.0});
        } else {
            campaign.fade({duration: 0.8});
        }
    }.bind(this));

    currentCampaign = i;
}

var campaignCount;

function loopCampaigns() {
    campaignChangeTo((currentCampaign + 1) % campaignCount);
}

/* Add caption to images in articles */
/* Also adds shadow */

var ImgCaption = Class.create({

	initialize: function() {
		objBody = document.getElementsByTagName('body').item(0);
		var i = 0;
		 $$(".full-articledisplay .tile-content img").each(function(element, i) {
		 	if((element.readAttribute('usemap') == null) || (element.readAttribute('usemap') == "")) {

		 	var captionObj = document.createElement('div');
		 	var captionObjText = document.createElement('div');

		 	var newImg = document.createElement('img');
		 	var link = document.createElement('a');
		 	var myparent = element.parentNode || element.parent;
		 	this.element = element;
		 	if(myparent.nodeName == "A") {
		 		this.element = myparent;
		 		link.href = myparent.href;
		 		link.title = myparent.title;
                                link.target = myparent.target;
		 		/*link.setAttribute('onclick', myparent.readAttribute('onclick'));*/
		 		link.onclick = myparent.onclick;
		 		link.appendChild(newImg);
		 		captionObj.appendChild(link);
		 		myparent = myparent.parentNode || myparent.parent;

		 	} else {
		 		captionObj.appendChild(newImg);
		 	};

		 	newImg.src = element.src;
		 	newImg.alt = element.alt;
                        newImg.title = element.title;
                        newImg.id = element.id;
                        element.removeClassName('cp-mmarchive-image-right');
                        element.removeClassName('cp-mmarchive-image-left');
                        newImg.className = element.className;

		    var marginV = '0';
		    if (element.vspace != -1) {
		    marginV = element.vspace;
		    }
		    var marginH = '0';
		    if (element.hspace != -1) {
		    marginH = element.hspace;
		    }

		    if ((marginH == '0') && (marginV == '0')) {
			$(captionObj).setStyle( {'float': element.align, 'textAlign': 'center', 'width': element.width+'px'});
		    } else {
		    	$(captionObj).setStyle( {'float': element.align, margin: marginV+'px '+marginH+'px', 'width': element.width+'px'});
		    }

		 	captionObj.setAttribute('id','caption'+i);
		 	captionObjText.setAttribute('id','captionText'+i);
			$(captionObj).toggleClassName('caption'+element.align);
			$(captionObjText).toggleClassName('captionText');

                        if (element.getAttribute('title') && element.getAttribute('title').length > 0) {
                            captionObjText.innerHTML = element.getAttribute('title');
                            captionObj.appendChild(captionObjText);
                        }

                        if (newImg.className == 'ramme') {
                            var top = element.height+6;
                            var imageWidth = element.width+6;
                            captionObj.setStyle({'background': 'url(/themes/commaxx/images/item-shadow-'+imageWidth+'.png) 0 '+top+'px no-repeat'});
                        }

			Element.replace(this.element,$(captionObj));
			i= i+1;
		 }
		});
	}
});

var caption;
document.observe('dom:loaded', function(event) {
	caption = new ImgCaption();
});

// Updates courselist and limits the list to selected system or place

function updatecourselist() {
    var searchString = $('courseselect').value.split(":");

    // Hide no-hits message
    $$(".courselist table tr.nohits").each(function(element, i) {
        element.hide();
    });

    // Hide all system-headers and courses
    if (searchString[1]) {
        $$(".courselist table tr.item").each(function(element, i) {
           element.hide();
        });
        $$(".courselist table tr.next_system").each(function(element, i) {
           element.hide();
        });

        var hits = 0;
        // Show for given system or place
        $$(".courselist table tr."+searchString[1]).each(function(element, i) {
            element.up().down().show(); // Show system-header
            element.show();
            hits++;
        });

        if (hits == 0) {
            $$(".courselist table tr.nohits").each(function(element, i) {
                element.show();
            });
        }

    } else {
        
        $$(".courselist table tr.next_system").each(function(element, i) {
           element.show();
        });
        $$(".courselist table tr.nohits").each(function(element, i) {
            element.hide();
        });
        $$(".courselist table tr.item").each(function(element, i) {
           element.show();
        });
    }
}

// gup, get url parameter
// http://www.netlobo.com/url_query_string_javascript.html

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// url decode
// http://www.webtoolkit.info/javascript-url-decode-encode.html

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

// Update contact-schemaes with header

function fillHeader() {
    var headerString = gup ('text');
    
    headerString = headerString.replace(/\+/gi," ");
    headerString = headerString.replace(/(<([^>]+)>)/ig,"");
    headerString = headerString.replace(/%C2%AE/, "");
    headerString = Url.decode(headerString);
    var alphaExp = /^[0-9a-zæøåöäA-ZÆØÅÖÄ\/ .,!\?':\-|]+$/;
    if(headerString.match(alphaExp)){    
         $$("input[id^=Overskrift]").each(function(element) {
           element.value = headerString;
         });
    }
}

//pads left
String.prototype.lpad = function(padString, length) {
	var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

function fillDates() {
    var selectId;
    var firstDate;
    var pairs = location.search.substring(1).split('&');
    for (var i = 0; i < pairs.length; i++) {
      var pair = pairs[i].split('=');
      if (pair[0].substring(0,5) == 'dates') {
            var date = new Date(pair[1]*1000);
            var dayString = ''+(date.getUTCDate()+1);
            var monthString = ''+(date.getMonth()+1);
            var yearString;

            if (date.getYear() > 2000) {yearString = date.getYear();}
            else {yearString = date.getYear()+1900;}

            var datestring = dayString.lpad("0",2) + '.' + monthString.lpad("0",2) + '.' + yearString;
            if (!firstDate) {firstDate = datestring;}
             $$("select[id^=dates]").each(function(element) {
               selectId = element.identify();
               element.insert('<option>'+datestring+'</option>');
             });
      }
    }

    var matchDate = (gup('date') ? gup('date') : firstDate);

    $$('#' + selectId + ' option').each(function(element) {
        if (element.value == matchDate) {
            element.selected = true;
        }
    });

}

var header;
var date;
document.observe('dom:loaded', function() {
	header = new fillHeader();
        dates = new fillDates();
});

