/*
-----------------------------------------------
sitename
Script: vdwUtil.js
Author: Ben Glassman
Organization: Vermont Design Works
Created: 
----------------------------------------------- */

vdwUtil = {
	init:function() {
		vdwUtil.mailtoFix('REMOVETHISBEFORESENDING');
		vdwUtil.preparePopups();
		vdwUtil.autoPopulate('input.populate');
	},
	mailtoFix:function(stringToRemove) {
		var links = document.getElementsByTagName('a');
		var removeText = new RegExp(stringToRemove);
		for (var i = 0; i < links.length; i++) {
			if (links[i].href.indexOf('mailto:') != -1) {
				links[i].href = links[i].href.replace(removeText, '');
				links[i].firstChild.nodeValue = links[i].firstChild.nodeValue.replace(removeText, '');
				links[i].firstChild.nodeValue = links[i].firstChild.nodeValue.replace(/mailto:/, '');
			}
		}
	},
	popUp:function(winURL, name, parameters) {
		window.open(winURL, name, parameters);
	},
	preparePopups:function() {
		if (!document.getElementsByTagName) return false;
		var lnks = document.getElementsByTagName("a");
		for (var i=0; i<lnks.length; i++) {
			if (lnks[i].className == "popup") {
				lnks[i].title+= " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "popup", "width=320,height=480");
					return false;
				}
			}
			else if (lnks[i].className == "external") {
				lnks[i].title+= " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "external", "");
					return false;
				}
			}
			else if (lnks[i].href != null && lnks[i].href.indexOf('.pdf') != -1) {
				lnks[i].title += " (opens in a new window)";
				lnks[i].onclick = function() {
					vdwUtil.popUp(this.getAttribute("href"), "pdf", "");
					return false;
				}
			}
		}
	},
	trimString:function(str) {
		return str.replace(/^\s*\n*\r*|\s*\n*\r*$/g,'');
	},
	fadeUp:function(element, red, green, blue) {
		if (element.fade) {
			clearTimeout(element.fade);
		}
		element.style.backgroundColor = 'rgb('+red+','+green+','+blue+')';
		if (red == 255 && green == 255 && blue == 255) {
			return;
		}
		var newred = red + Math.ceil((255-red)/10);
		var newgreen = green + Math.ceil((255-green)/10);
		var newblue = blue + Math.ceil((255-blue)/10);
		var repeat = function() {
			vdwUtil.fadeUp(element, newred, newgreen, newblue);
		}
		element.fade = setTimeout(repeat, 100);
	},
	autoPopulate:function(input_sel) {	
		$jq(input_sel).each(function() {
			var populate_text = $jq('label[for="' + $jq(this).attr('id') + '"]').text();
			if (populate_text) {
				$jq(this).val(populate_text).data('populate_text', populate_text);				
				$jq(this).focus(function() {
					if ($jq(this).val() == $jq(this).data('populate_text')) {
						$jq(this).val('');
					}
				});
				$jq(this).blur(function() {
					if ($jq(this).val() == '') {
						$jq(this).val($jq(this).data('populate_text'));
					}
				});
			}
		});
	},
	initPollQuestionForm : function() {
/*
		var minHeight = Number($jq('#module-polls').height());
		if ($jq('#module-polls').css('paddingTop')) { minHeight = minHeight - Number($jq('#module-polls').css('paddingTop').replace('px', '')); }
		if ($jq('#module-polls').css('paddingBottom')) { minHeight = minHeight - Number($jq('#module-polls').css('paddingTop').replace('px', '')); }
		$jq('#module-polls').css('minHeight', minHeight);
*/
		$jq('.polls-form').submit(function(e) {
			e.preventDefault();
			var poll_question_id = $jq('#poll_question_id').val();
			var data = {
				'poll_question_id' : $jq('#poll_question_id').val(),
				'polls_mode' : $jq('#polls_mode').val(),
				'poll_question_option_id' : $jq('input[name="poll_question_option_id"]:checked').val()
			}
			$jq('#module-polls .module-content').html('<div style="text-align: center;"><img src="/assets/templates/main/images/loading.gif" /></div>');
			$jq.ajax({
				type : 'GET',
				url : '/poll-ajax-handler',
				data : data,
				success : function(data) {
					$jq.cookie('blcp_poll' + poll_question_id, '1');
					$jq('#module-polls').html($jq(data).html());
				}
			});
		});
		$jq('.polls-form .btn-view-results').click(function(e) {
			e.preventDefault();
			$jq('#module-polls .module-content').html('<div style="text-align: center;"><img src="/assets/templates/main/images/loading.gif" /></div>');
			$jq.ajax({
				type : 'GET',
				url : '/poll-ajax-handler',
				data : $jq(this).attr('href').replace(/^.+?\?/, ''),
				success : function(data) {
					$jq('#module-polls').html($jq(data).html());
				}
			});
		});
	},
	initViewQuestionResults : function(results) {
		this.results = results;
		//Load the Visualization API and the Google Pie Chart visualization
		google.load('visualization', '1', {'packages':['corechart']});
		google.setOnLoadCallback(vdwUtil.drawQuestionResultsChart);
	},
	drawQuestionResultsChart : function() {
		var self = vdwUtil;
		// Create and populate the data table.
		var data = new google.visualization.DataTable();
		for (var i = 0; i < self.results.columns.length; i++) {
		  data.addColumn(self.results.columns[i]['type'], 0, self.results.columns[i]['name']);
		}
		data.addRows(self.results.total_rows);
		for (var i = 0; i < self.results.rows.length; i++) {
		  data.setValue(i, 0, self.results.rows[i]['answer']);
		  data.setValue(i, 1, self.results.rows[i]['response_count']);
		}
		// Create and draw the visualization.
		new google.visualization.PieChart(document.getElementById('visualization')).
		  draw(data, { backgroundColor : '#ECF4FF', width: 220, height: 220 });	

	}
}

vdwDOM = {
	addEvent:function(elm, evType, fn, useCapture){
		if (elm.addEventListener){
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			elm['on' + evType] = fn;
		}
	},
	getTarget:function(e){
		var target = window.event ? window.event.srcElement : e ? e.target : null;
		if (!target){return false;}
		while(target.nodeType!=1 && target.nodeName.toLowerCase()!='body'){
			target=target.parentNode;
		}
		return target;
	},
	cancelClick:function(e){
		if (window.event){
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault){
			e.stopPropagation();
			e.preventDefault();
		}
	},
    safariClickFix:function(){
      return false;
    },
	addClass:function(element, value) {
		if (!element.className) {
			element.className = value;
		} else {
			newClassName = element.className;
			newClassName+= " ";
			newClassName+= value;
			element.className = newClassName;
		}
	},
	removeClass:function(element, value) {
		var rep = element.className.match(' '+value)?' '+value:value;
		element.className = element.className.replace(rep,'');
	},
	importNode:function(node, allChildren) {
		/* find the node type to import */
		switch (node.nodeType) {
			case document.ELEMENT_NODE:
				/* create a new element */
				var newNode = document.createElement(node.nodeName);
				/* does the node have any attributes to add? */
				if (node.attributes && node.attributes.length > 0)
					/* add all of the attributes */
					for (var i = 0, il = node.attributes.length; i < il;)
						newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i++].nodeName));
				/* are we going after children too, and does the node have any? */
				if (allChildren && node.childNodes && node.childNodes.length > 0)
					/* recursively get all of the child nodes */
					for (var i = 0, il = node.childNodes.length; i < il;)
						newNode.appendChild(vdwDOM.importNode(node.childNodes[i++], allChildren));
				return newNode;
				break;
			case document.TEXT_NODE:
			case document.CDATA_SECTION_NODE:
			case document.COMMENT_NODE:
				return document.createTextNode(node.nodeValue);
				break;
		}
	},
	firstChild:function(parent, nodeType) {
		var child = parent.firstChild;
		while (child.nodeType != nodeType) {
			child = child.nextSibling;
		}
		return child;		
	},
	/*
    getElementsByClassName
    Written by Jonathan Snook, http://www.snook.ca/jonathan
    Add-ons by Robert Nyman, http://www.robertnyman.com
	*/
	getElementsByClassName:function(oElm, strTagName, oClassNames){
		var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
		var arrReturnElements = new Array();
		var arrRegExpClassNames = new Array();
		if(typeof oClassNames == "object"){
			for(var i=0; i<oClassNames.length; i++){
				arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
			}
		}
		else{
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
		}
		var oElement;
		var bMatchesAll;
		for(var j=0; j<arrElements.length; j++){
			oElement = arrElements[j];
			bMatchesAll = true;
			for(var k=0; k<arrRegExpClassNames.length; k++){
				if(!arrRegExpClassNames[k].test(oElement.className)){
					bMatchesAll = false;
					break;
				}
			}
			if(bMatchesAll){
				arrReturnElements.push(oElement);
			}
		}
		return (arrReturnElements)
	},
	fixNodeTypes:function() {
		/* Make sure that all the necessary node types for vdwDOM.importNode are defined */
		if (!document.ELEMENT_NODE) {
			document.ELEMENT_NODE = 1;
			document.ATTRIBUTE_NODE = 2;
			document.TEXT_NODE = 3;
			document.CDATA_SECTION_NODE = 4;
			document.ENTITY_REFERENCE_NODE = 5;
			document.ENTITY_NODE = 6;
			document.PROCESSING_INSTRUCTION_NODE = 7;
			document.COMMENT_NODE = 8;
			document.DOCUMENT_NODE = 9;
			document.DOCUMENT_TYPE_NODE = 10;
			document.DOCUMENT_FRAGMENT_NODE = 11;
			document.NOTATION_NODE = 12;
		}	
	}
}

// ---
// Array support for the push method in IE 5
if(typeof Array.prototype.push != "function"){
	Array.prototype.push = ArrayPush;
	function ArrayPush(value){
		this[this.length] = value;
	}
}
// ---
/*
	Examples of how to call the function:
	
	To get all a elements in the document with a "info-links" class:
    getElementsByClassName(document, "a", "info-links");
    
	To get all div elements within the element named "container", with a "col" and a "left" class:
    getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]);
*/
// ---

/*sfHover = function() {
	if (document.getElementById('navigation')) {
		var sfEls = document.getElementById("navigation").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);*/

vdwDOM.addEvent(window, 'load', vdwUtil.init, false);

/*
jQuery Form Validation Error Container Plugin */

jQuery.fn.prepareFormVal = function() {
    return this.each(function(){
        jQuery('<div id="error-container"><h2>The following errors occured</h2><ul></ul></div>').prependTo(jQuery(this)).hide();
    });
};

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};