/*
    SiteComponents version:
    Id: site.js,v 1.7 2009/05/08 13:28:17 kurt Exp 
    Name: SC_6_6_0_1 

    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
    
    /*
    // Use this to move the collapsed debug position to the left, instead
    // of the default right.
    'debug': {
        'collapsedPageInfoPosition': 'left'
    }
    */
    
    /*
    // 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': {
        'positionby': 'mouse'
    }
    */
    
    // Use this to override the default fontsizes in the fontsize selector
    // (html/lib/fontsize.js)
    
    'fontsize': {
        'sizes': ["12px", "15pt", "24pt"]
    }
    
};

var Collapser = Class.create({
	initialize: function() {
		var i = 0;
		var container;
		var linkelement;
		var exists = false; 
		
		 $$(".collapsed-tabbed-main").each(function(element, i) {
		 	container = element.down().next('.tile-content');
			element.select('.tile-content').first().update('<div id="linkContainer" class="linkContainer"></div><div id="contentContainer" class="contentContainer"></div>');
                  element.style.display = 'block';
		});	
	
		 $$(".collapsable-main").each(function(element, i) {
		 	linkelement = new Element('h4', {'id' : 'linkElement'+i}).update(element.down().next('h3').innerHTML);
		 	linkelement.onclick = function () { collapseControl.collapseToggle('linkElement'+i,'contentElement'+i); }
		 	$('linkContainer').insert (linkelement);
		 	$('contentContainer').insert (new Element('div', {'id' : 'contentElement' + i}).update(element.down().next('.tile-content').innerHTML).hide());
			element.remove();
			exists = true;
		});
		 if (exists == false) { 
			 $$(".collapsed-tabbed-main").each(function(element, i) {
				 element.style.display = 'none';
			 } 
		 )};
		 
		if (exists == true && (window.contentContainer || document.getElementById('contentContainer'))) {
			$('contentContainer').down().show();
			$('linkContainer').firstDescendant().addClassName('active');
		}
	
	},
	
	collapseToggle: function(link, content) {
		$$(".linkContainer").each(function(element, i) { element.childElements().each(function(child,j) {child.removeClassName('active'); })});
		$$(".contentContainer").each(function(element, i) { element.childElements().each(function(child,j) {child.hide(); })});
		$(link).addClassName('active');
		$(content).show();
	}
});

var collapseControl;
document.observe('dom:loaded', function(event) {
	collapseControl = new Collapser();
});



/**
 * FlogUriParser is freely distributable under the terms of an MIT-style license.
 *
 * Copyright (c) 2006 Adam Burmister, Original author Poly9.com
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * ------------------------------------------------------------------------------------
 *
 * @author Adam Burmister, adam.burmister@gmail.com, www.flog.co.nz
 * @version 0.1
 * @namespace Flog
 *
 * Based on the Poly9.com url parser, modified to Prototype class and javascript conventions
 *
 * Usage: var p = new Flog.UriParser('http://user:password@flog.co.nz/pathname?arguments=1#fragment');
 * p.host == 'flog.co.nz';
 * p.protocol == 'http';
 * p.pathname == '/pathname';
 * p.querystring == 'arguements=1';
 * p.querystring[arguements] | p.querystring.arguements == 1
 * p.fragment == 'fragment';
 * p.user == 'user';
 * p.password == 'password';
 *
 */

/* Fake a Flog.* namespace */
if(typeof(Flog) == 'undefined') var Flog = {};

Flog.UriParser = Class.create();

/* A prototype modification of poly9.com's original parser */
Flog.UriParser.prototype = {
	_regExp : /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/,
	username : null,
	password : null,
	port : null,
	protocol : null,
	host : null,
	pathname : null,
	url : null,
	querystring : {},
	fragment : null,

	initialize: function(uri) {
		if(uri) this.parse(uri);
	},

	_getVal : function(r, i) {
		if(!r) return null;
		return (typeof(r[i]) == 'undefined' ? null : r[i]);
	},

	parse: function(uri) {
		var r = this._regExp.exec(uri);
		if (!r) throw "FlogUriParser::parse -> Invalid URI"
		this.url		= this._getVal(r,0);
		this.protocol	= this._getVal(r,2);
		this.username	= this._getVal(r,4);
		this.password	= this._getVal(r,5);
		this.host		= this._getVal(r,6);
		this.port		= this._getVal(r,7);
		this.pathname	= this._getVal(r,8);
		this.querystring= new Flog.UriParser.QueryString(this._getVal(r,9));
		this.fragment	= this._getVal(r,10);
		return r;
	}
};

/* Querystring sub class */
Flog.UriParser.QueryString = Class.create();
Flog.UriParser.QueryString.prototype = {
	rawQueryString : '',
	length : 0,
	initialize : function(qs) {
		if(!qs) {
			this.rawQueryString = '';
			this.length = 0;
			return;
		}
		this.rawQueryString = qs;
		var args = qs.split('&');
		this.length = args.length;
		for (var i=0;i<args.length;i++) {
			var pair = args[i].split('=');
			this[unescape(pair[0])] = ((pair.length == 2) ? unescape(pair[1]) : pair[0]);
		}
	},
	toString : function() {
		return this.rawQueryString;
	}
};


// FormResult search functionality

if(typeof(NNV) == 'undefined') var NNV = {};

NNV.FormResultSearcher = Class.create();

NNV.FormResultSearcher.prototype = {

    anchor: '',

    initialize: function(anchorId) {
        this.anchor = anchorId;
    },

    _getVal : function(r, i) {
		if(!r) return null;
		return (typeof(r[i]) == 'undefined' ? null : r[i]);
    },
    
    crit_redirect : function(form) {
        //var anchor = 'FormResult-' + form.formTemplateId.value;
        var newCritValue = form.searchvalue.value;
        if (newCritValue.length == 0) {
            return false;
        }
        var newCritField = form.crit.value;
        var uriParser = new Flog.UriParser(document.location.href);
        var urlVars = this.getUrlVars(uriParser.querystring);

        urlVars['crit[' + newCritField + ']'] = newCritValue;
        var newParamString = '';
        for (var key in urlVars) {
            if (key.length>6 && urlVars[key] != undefined) {
                newParamString += key + '=' + urlVars[key] + '&';
            }
        }
        document.location = 'http://' + uriParser.host + uriParser.pathname + '?' + newParamString + '#'+ this.anchor;
        return false;
    },
    getUrlVars : function(queryString) {
        var result = {};
        if (queryString != undefined) {
            var parameters = queryString.toString().split('&');
            for(var i = 0;  i < parameters.length; i++) {
                var parameter = parameters[i].split('=');
                result[parameter[0]] = parameter[1];
            }
        }
        return result;
    },
    resetSearch : function(form) {
        var curUrl = document.location.href.split("?");
        document.location = curUrl[0] + '#' + this.anchor;
        return false;
    }
}

