var QueryString = Class.create({
	initialize : function (options) {
		this.options = {
			separator: '?'
		}
		Object.extend(this.options, options || {});
		
		this.url = location.toString();
		this.qs = this.url.split(this.options.separator)[1];
		(this.qs) ? this.qsPairs = this.qs.split("&") : this.qsPairs = [];
	},
	
	hasQueryString : function() {
		(this.qs) ? r=true : r=false;
		return r;
	},
	
	hasParameter : function(p) {
		(this.qs.indexOf(p) != -1) ? r=true : r=false;
		return r;
	},
	getQueryString : function() {
		return this.qs;
	},
	
	getParameter : function(p) {
		if (this.hasParameter(p)) {
			for(i=0;i<this.qsPairs.length; i++) {
				if (this.qsPairs[i].split("=")[0] == p) {
					r = this.qsPairs[i].split("=")[1];
				}
			}
		}
		else {
			r = null;
		}
		return r;
	}
});

var CaseStudies = Class.create({
	initialize : function(obj, options) {
		this.options = {
			mOverBGcolor: '#f5f5f5',
			mOutBGcolor: '#fff'
		};
		this.obj = Element.extend(document.getElementById(obj));
		Object.extend(this.options, options || {});

		scope = this;
		this.containers = this.obj.childElements();
		this.containers.each(function(c) {
			c.onmouseover = function() {this.setStyle({'background': scope.options.mOverBGcolor})};
			c.onmouseout = function() {this.setStyle({'background': scope.options.mOutBGcolor})};		
		});
		
		this.links = $$('.' + this.containers[0].className + ' a.expander');
		this.links.each(function(lnk) {Event.observe(lnk,"mouseup",scope.toggle);});
		this.openCaseStudy = null;
	},
	toggle : function(trigger) {
		Object.extend(trigger);
		if (Object.inspect(trigger) == "[object MouseEvent]" || Object.inspect(trigger) == "[object Event]") {
			lnk = this;
			current = this.next();
		}
		else {
			lnk = $(trigger).previous();
			current = $(trigger);
		}
		
		//nothing is open, so open the selected case study
		if(scope.openCaseStudy == null) {
			new Effect.toggle(current,'blind', {duration:0.5, queue: {position:'end', scope:'casestudy'}, afterFinish: function() {new Effect.ScrollTo(current.up(), {offset: -15, duration:0.5});}});
			scope.openCaseStudy = current;
			lnk.innerHTML = "Close case study"; 
			lnk.setStyle({'background': 'url(/wp-content/themes/commune2.0/images/greenArrowUp.gif) right no-repeat'});
			lnk.up().onmouseover = null; 
			lnk.up().onmouseout = null; 
			lnk.up().setStyle({'background': '#f5f5f5'});
			pageTracker._trackPageview(lnk.href);
		}
		
		//close the currently open case study
		else if(scope.openCaseStudy == lnk.next()) {
			new Effect.toggle(current,'blind', {duration:0.5, queue: {position:'end', scope:'casestudy'}});
			scope.openCaseStudy = null;
			lnk.innerHTML = "Read case study"; 
			lnk.setStyle({'background': 'url(/wp-content/themes/commune2.0/images/greenArrowDown.gif) right no-repeat'});
			lnk.up().onmouseover = function() {this.setStyle({'background': '#f5f5f5'})};
			lnk.up().onmouseout = function() {this.setStyle({'background': '#fff'})};
		}
		
		//close the currently open case study and open the newly selected one
		else {
			new Effect.Parallel([
				new Effect.BlindDown(current, {sync: true}), 
				new Effect.BlindUp(scope.openCaseStudy, {sync: true})
			], {duration: 0.5, queue: {position:'end', scope:'casestudy'}, afterFinish: function() {new Effect.ScrollTo(current.up(), {offset: -15, duration:0.5});}});
			lnk.innerHTML = "Close case study"; 
			lnk.setStyle({'background': 'url(/wp-content/themes/commune2.0/images/greenArrowUp.gif) right no-repeat'});
			lnk.up().onmouseover = null; 
			lnk.up().onmouseout = null; 
			lnk.up().setStyle({'background': '#f5f5f5'});
			scope.openCaseStudy.previous().innerHTML = "Read case study"; 
			scope.openCaseStudy.previous().setStyle({'background': 'url(/wp-content/themes/commune2.0/images/greenArrowDown.gif) right no-repeat'});
			scope.openCaseStudy.up().onmouseover = function() {this.setStyle({'background': '#f5f5f5'})};
			scope.openCaseStudy.up().onmouseout = function() {this.setStyle({'background': '#fff'})};
			scope.openCaseStudy.up().setStyle({'background': '#fff'});
			scope.openCaseStudy = current;
			pageTracker._trackPageview(lnk.href);
		}
	}
});

var GoogleMap = Class.create({
	initialize : function() {
		this.loadMap();
	}, 
	
	loadMap : function() {
		if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById("map"));
			var start = new GLatLng(43.6502959, -79.376289);
			var end = new GLatLng(43.6500072, -79.3740631);
			var blnProperPos = false;
			
			//geocoder = new GClientGeocoder(); geocoder.getLatLng("100 King St., E., Toronto, ON", function(p) {alert(p);});
			
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(start, 15);
			map.openInfoWindowHtml(map.getCenter(), "<h4>Commune Media Inc.</h4>36 Toronto St., Suite 850<br />Toronto, ON, Canada,<br />M5C 2C5");
			
			var listenInfoWindowMovement = GEvent.addListener(map, "moveend", function() {
				if ( !blnProperPos ) {
					map.panTo(end);
					blnProperPos = true;
				} else {
					GEvent.removeListener(listenInfoWindowMovement);
				}
			});
		
		// add the map marker
		map.addOverlay(new GMarker(start));
		}
	}
});

var formSubmit = Class.create({
	initialize : function(obj,options) {
		this.options = {
			method : 'post',
			type : 'contact', 															 // TYPE - required - can be 'contact' or 'comment'
			url : '', 																	 // URL - required
			errorMsg : 'Error in submit',												 // ERRORMSG - required - should override
			successMsg : 'Submit was successful',										 // SUCCESSMSG - required -  should override
			//optional fields only used by SalesForce next
			oid	 : '',       															 // OID - if type==contact, then required -- used in SalesForce submission
			retURL : ''																	 // RETURL - used in SalesForce submission
		};
		
		this.obj = Element.extend(document.getElementById(obj));
		Object.extend(this.options, options || {});
		this.el = this.obj.getElements();
		scope = this;
		$('submit').onmouseup = function(){scope.validate();};
	},
	
	validate : function(e) {
		haveError = false;
		for(i in this.el) this.el[i].error = false;
		
		//DEFINE REGULAR EXPRESSIONS
		nameExpr   = /^([a-zA-Z '-]+)$/i;
		emailExpr  = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z \.])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$/i;
		phoneExpr  = /^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/i; 
		urlExpr    = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$/i;
		
		//Validate contact form fields
		if(this.options.type == 'contact') {
			if (!nameExpr.test(this.el[0].value)) this.el[0].error = true;								// Validate first name
			if (!nameExpr.test(this.el[1].value)) this.el[1].error = true;								// Validate last name
			if (!emailExpr.test(this.el[2].value)) this.el[2].error = true;								// Validate email address
			if(!this.el[3].value.blank()) { 															// Validate phone number
				if (!phoneExpr.test(this.formatPhoneNumber(this.el[3].value))) this.el[3].error = true;
			}
				
			if (!nameExpr.test(this.el[4].value)) this.el[4].error = true;								// Validate company name
			
			if(!this.el[5].value.blank()) { 															// Validate website url
				if (!urlExpr.test(this.el[5].value)) this.el[5].error = true;
			}
			if (this.el[6].value.blank()) this.el[6].error = true;										// Validate message
	
			//loop through errors, if any
			for(i=0; i<this.el.length-1; i++) {
				if(this.el[i].error == true) {
					this.el[i].style.backgroundColor = "#FFFF99";
					haveError = true;
				}
				else {
					this.el[i].style.backgroundColor = "#ffffff";
				}
			}
		}
		
		//Validate comment form fields
		else {
			if (!nameExpr.test(this.el[0].value)) this.el[0].error = true;								// Validate name field
			if (!emailExpr.test(this.el[1].value)) this.el[1].error = true;								// Validate email address
			if(!this.el[2].value.blank()) { 															// Validate website url
				if (!urlExpr.test(this.el[2].value)) this.el[2].error = true;
			}
			if (this.el[3].value.blank()) this.el[3].error = true;										// Validate message
	
			//loop through errors, if any
			for(i=0; i<4; i++) {
				if(this.el[i].error == true) {
					this.el[i].style.backgroundColor = "#FFFF99";
					haveError = true;
				}
				else {
					this.el[i].style.backgroundColor = "#ffffff";
				}
			}
		}
		
		if(haveError) {
			if(!$$('.contactFormError').length) {
				msg = document.createElement("div");
				Element.extend(msg);
				msg.update(this.options.errorMsg);
				msg.className = "contactFormError";
				this.obj.parentNode.insert(msg);
				//new Effect.Highlight(msg);
				window.setTimeout('Element.remove(msg)',10000);
			}
			return false;
		}
		else {
			if($$('.contactFormError').length) Element.remove(msg);
			this.submit();
		}
	},
	
	formatPhoneNumber : function(p) {
		filteredValues = "()- ";
		var formattedNumber = "";
		
		for (i=0; i<p.length; i++) {  // Search through string and append to unfiltered values to returnString.
			c = p.charAt(i);
			if (filteredValues.indexOf(c) == -1) formattedNumber += c;
		}
		
		return formattedNumber;
	},
	
	submit : function() {
		console.log('submit');
		scope = this;
		params = this.obj.serialize();
		if(this.options.type == 'contact') {
			params+= '&postURL=' + encodeURIComponent(this.options.url) + '&oid=' + this.options.oid + '&retURL=' + encodeURIComponent(this.options.retURL);
			url = '/wp-content/themes/commune2.0/proxy.php';
		}
		else
			url = this.options.url;
			
		new Ajax.Request(url, {
			method: this.options.method,
			parameters: params,
			on200: function(transport) {
				_gaq.push(['_trackPageview("/'+scope.options.type+'/thanks/")']);
				scope.obj.reset();
				msg = document.createElement("div");
				Element.extend(msg);
				msg.update(scope.options.successMsg);
				msg.className = "contactFormSuccess";
				scope.obj.parentNode.insert(msg);
				new Effect.Highlight(msg);
				window.setTimeout('Element.remove(msg)',15000);
			}
		});
	}
});



function ieMakeTransparentPNGs() {

    if (
        ((navigator.userAgent.toLowerCase()).indexOf('msie') + 1) &&      //'+1' because indexOf returns -1 if string is not found
        ((navigator.userAgent.toLowerCase()).indexOf('windows') + 1)  &&
        !((navigator.userAgent.toLowerCase()).indexOf('opera') + 1)       //Opera reports itself as MSIE/Windows, but also adds an 'Opera' string
        ) {

        for (i=0;i<document.images.length;i++) {
            if (document.images[i].src.toLowerCase().indexOf('.png') + 1) {
                var pngImage = document.images[i];
                pngImage.style.width = pngImage.offsetWidth;
                pngImage.style.height = pngImage.offsetHeight;
                pngImage.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+pngImage.src+"',sizingMethod='scale');";
                pngImage.src = '/wp-content/themes/commune2.0/images/blank.gif';
            }
        }
    }
}