//
//	Set up all accordions
//
function loadAccordions() {
				
	var bottomAccordion = new accordion('test-accordion',
	{
	onActivate : MyCallBack,
	RepeatActivate : { dynamicduo: false }
	}
	);	
		
	// Open first one
	bottomAccordion.activate($$('#test-accordion .accordion_toggle')[0]);	

}

function fnAJAXIT(url, updateelem)
{
		
$(updateelem).innerHTML = 'Loading....';

//I usualled throw in some Spinny animated Gif here.

var ajax = new Ajax.Request(url , 
	{ 
		onSuccess :  ajax_text,
		parameters : 'updateelem=' + updateelem
	}
   );

}

		
function MyCallBack(elem)
{
var elemid = $(elem).id;
}

var dim = [ 
	{relType: "popup-video", width:350, height:260},
	{relType: "popup-short", width:585, height:128},
	{relType: "popup", width:580, height:600},
	{relType: "contact", width:730, height:600}];

// Function to create popup windows
function openWindow(evt) {
	var el = Event.findElement(evt, 'a');

	var prop = dim.detect( function(item) {
	//	return (item.relType == el.rel);
		return (el.rel.indexOf(item.relType) != -1);
	} );

	window.open(el.href, "newwindow", 'toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes,status=no, width='+prop.width+',height='+prop.height+'');
	Event.stop(evt);
}

// Create popup windows based on the rel attribute of links
function relPopups() {
	var allLinks = $A(document.getElementsByTagName('a'));
	allLinks.each(function(item) {
		var rel = item.rel;
		if (rel != null && rel != "") {
			// Look for rel value in dim
			var relExists = dim.detect( function(s) {
			//	return (s.relType == rel)
				return (rel.indexOf(s.relType) != -1)
			})
			
			// If rel is specified, attach openWindow function
			if(relExists) {
				$(item).observe('click', openWindow);
			}
		}
	});
}


/*
 * Fabtabulous! Simple tabs using Prototype
 * http://tetlaw.id.au/view/blog/fabtabulous-simple-tabs-using-prototype/
 * Andrew Tetlaw
 * version 1.1 2006-05-06
 * http://creativecommons.org/licenses/by-sa/2.5/
 */
var Fabtabs = Class.create();

Fabtabs.prototype = {
	initialize : function(element) {
		this.element = $(element);
		var options = Object.extend({}, arguments[1] || {});
		this.menu = $A(this.element.getElementsByTagName('a'));
		this.show(this.getInitialTab());
		this.menu.each(this.setupTab.bind(this));
	},
	setupTab : function(elm) {
		Event.observe(elm,'click',this.activate.bindAsEventListener(this),false)
	},
	activate :  function(ev) {
		var elm = Event.findElement(ev, "a");
		Event.stop(ev);
		this.show(elm);
		this.menu.without(elm).each(this.hide.bind(this));
		// window.location.hash = this.tabID(elm);
	},
	hide : function(elm) {
		$(elm).removeClassName('active-tab');
		$(this.tabID(elm)).removeClassName('active-tab-body');
	},
	show : function(elm) {
		$(elm).addClassName('active-tab');
		$(this.tabID(elm)).addClassName('active-tab-body');

	},
	tabID : function(elm) {
		return elm.href.match(/#(\w.+)/)[1];
	},
	getInitialTab : function() {
		if(document.location.href.match(/#(\w.+)/)) {
			var loc = RegExp.$1;
			var elm = this.menu.find(function(value) { return value.href.match(/#(\w.+)/)[1] == loc; });
			return elm || this.menu.first();
		} else {
			return this.menu.first();
		}
	}
}


// SWFOBJECT MOVIES
var params = {
  	allowfullscreen: "true",
  	allowscriptaccess: "always",
	wmode: "transparent"
	};
	var flashvars = {
  	autostart: "true",
  	enablejs: "true",
  	searchbar: false,
  	linkfromdisplay: false,
  	showdownload: false
  	};
var attributes = {};

function initFlvPlayer(){

	if ($('reimbursementswf').hasClassName('mediaplayer')) { 
		flashvars.file = "vehicles/services/gm_mobility/media/swf/08mob-reimbursment.swf";
		flashvars.image = "/vehicles/services/gm_mobility/images/pic/get-application.jpg";
		flashvars.autostart = "false";
		flashvars.displayheight = "172";
		swfobject.createCSS("#reimbursementswf", "width:261; height:172;");									swfobject.embedSWF("/vehicles/services/gm_mobility/media/swf/08mob-reimbursment.swf","reimbursementswf","261","172","8.0.0", "/vehicles/services/gm_mobility/media/swf/expressInstall.swf", flashvars, params, attributes);
	}

	if ($('onstarvideo').hasClassName('mediaplayer')) { 
		flashvars.file = "/vehicles/services/gm_mobility/media/swf/video_player.swf";
		flashvars.image = "/vehicles/services/gm_mobility/images/pic/video_player_backup.jpg";
		flashvars.autostart = "false";
		flashvars.displayheight = "475";
		swfobject.createCSS("#onstarswf", "width:350; height:475;");
		swfobject.embedSWF("/vehicles/services/gm_mobility/media/swf/video_player.swf","onstarvideo","350","475","8.0.0", "/vehicles/services/gm_mobility/media/swf/expressInstall.swf", flashvars, params, attributes);
	}
}

// Create external links in new windows
function openExternal() {
	$$('a[rel~="external"]').each(function(link) {
	link.target = "_blank";
	});
}

/* request-app */
var valid;

		
	if( $('request-app') ) {
	
		document.forms[0].setAttribute('autocomplete', 'off');
		valid = new Validation(document.forms[0], {immediate : true, onElementValidate: highlight });
		submitMailOnclick = function() { $('ThankYou').value = "/vehicles/services/gm_mobility/content/reimbursement/request-an-application/thank-you/index.jsp"; }
		submitOnlineOnclick = function() { $('ThankYou').value = "/vehicles/services/gm_mobility/content/reimbursement/request-an-application/thank-you/index.jsp"; }
		Event.observe($('mail-03611'), 'click', submitMailOnclick);
		Event.observe($('online-03611'), 'click', submitOnlineOnclick);
		if (document.location.search.indexOf("selected=online") != -1) { $("online-03611").checked = true; $('ThankYou').value = "/vehicles/services/gm_mobility/reimbursement/request-an-application/";}
		else if (document.location.search.indexOf("selected=mail") != -1) { $("mail-03611").checked = true; $('ThankYou').value = "/vehicles/services/gm_mobility/content/reimbursement/request-an-application/thank-you/";}

		Validation.addAllThese([
			['validate-us-ca-postal', 'Please enter a valid United States Zip Code or Canadian Postal Code', function(v) {
				v = v.toUpperCase();
			    return Validation.get('IsEmpty').test(v) ||  /(\d{5}(.?\d{4})?$)|([A-Z]\d[A-Z] \d[A-Z]\d$)/.test(v);
					}],
			['validate-zip', 'Please enter a valid zip code.Ex:"12345" or "12345-6789"', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^\d{5}([\-]\d{4})?$/.test(v);
					}],
			['validate-city', 'Please use letters only (a-z) in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  /^([A-Za-z-\/\']+ ?)+$/.test(v);
					}] 
			]);
		}
		
	if($('forward-to-friend') ) {
		document.forms[0].setAttribute('autocomplete', 'off');
		valid = new Validation(document.forms[0], {immediate : true, onElementValidate: highlight });
		textAreaClear = function() {
			if (this.defaultValue == this.value) this.value = "";
			}
		Event.observe($('Message'), 'focus', textAreaClear );
		}

/*	$$('#pContent a[href^=http]').each( function(a) {
			a.style.background = "#88ff88";
		}); */

	$$('#pContent dt a.accessory').each( function(a) {
/*			a.style.background = "#8888ff"; */
			Event.observe(a, 'click', function(event) { popUpWindow(a.href,'form','width=300,height=302,scrolling=no'); Event.stop(event); });
		});
		
	$$('a[rel~=external]').each( function(a) {
	/*		a.style.background = "#ff8888"; */
			Event.observe(a, 'click', function(event) { popUpWindow(a.href,'form','width=800,height=600,location=1,resizable=1'); Event.stop(event); });
		});
		
	$$('a[rel~=video]').each( function(a) {
	/*		a.style.background = "#ff8888"; */
			Event.observe(a, 'click', function(event) { popUpWindow(a.href,'form','width=320,height=240,location=0,resizable=0,scrollbars=0,menubar=0,status=0'); Event.stop(event); });
		});

	$$('a[rel~=form]').each( function(a) {
/*			a.style.background = "#ff8888"; */
			Event.observe(a, 'click', function(event) { popUpWindow(a.href,'form','width=490,height=600'); Event.stop(event); });
		});

	$$('a[rel~=extform]').each( function(a) {
/*			a.style.background = "#ff8888"; */
			Event.observe(a, 'click', function(event) { popUpWindow(a.href,'form','width=780,height=500'); Event.stop(event); });
		});
		

/*	$$('#pContent a[href$=pdf]').each( function(a) {
			a.style.background = "#ff88ff";
		}); */

	$$('#sidebar div.section dt a[href~=' + document.location.pathname + '], #sidebar dt a[href~=' + document.location.pathname + ']').each( function(a) {
			a.style.color = "#000000";
			a.style.cursor = "default";
			// a.onclick = function() { return false; };
			// a.style.fontStyle = "italic";			
		});


	$$('#onstarswf li a').each( function(a) {
			a.onclick = function() { return false; };		
		});

	

function initSaf() {
	$A(document.forms).each(function(item) {
		var f = $(item);
		if (f.hasClassName('safajax') ) {
	 		Event.observe(f, 'submit', safUpdate.bindAsEventListener(this) );
	 		Form.getElements(f).each(function(item) {
	 			if(item.hasClassName('submit-direct') && item.value != ""){
	 				safUpdate(f);
	 				if($('submitForm')){
	 					$('submitForm').disabled = false;
	 				}
	 			}
			
	 		});
		}else if (f.hasClassName('shadowAction') ) {
	 		Event.observe(f, 'submit', initShadowAction.bindAsEventListener(this) );
	 	}
	} );
}


function submitbutton(){

	$$('input').each(function(item){
		
			if(item.type=='image' && item.title != "" ){
				item.onclick=function(){
					clickTrack({s_linkName:item.title})
				}
			}
		
	})
	
}

/*function safUpdate(evt){
	var form = Event.findElement(evt, 'form');
	var url = form.action + "result.jsp";
	var pars = Form.serialize(form);
	var opt = {
		method: "post",
		postBody: pars ,
		onSuccess: function(transport) {
			if($('results')){
				$('results').innerHTML = transport.responseText;
			}
			
		},
		on404: function(t) {
			 Firelog.log("Error 404: location " + xhr.statusText + " was not found.");
		},
		onFailure: function(t) {
			Firelog.log("Validate Method Error " + xhr.status + " -- " + xhr.statusText);
		}
	}
//	
	Event.stop(evt);
	new Ajax.Request(url, opt);
}
*/

function safUpdate(evt){
	if(evt.action){
		var form = evt;
	}else{
		Event.stop(evt);
		var form = Event.findElement(evt, 'form');
	}
	var url = form.action;
	
	var pars = Form.serialize(form);
	var opt = {
		method: "post",
		postBody: pars ,
		onSuccess: function(transport) {
			var found = false;
			if($('results')){
				$('results').removeAllChildren();
				if(form["state"].value=="" || form["state"].value=="Choose a State"){
					var p = document.createElement("p");
					p.appendChild(document.createTextNode("Please select a state."));
					$('results').appendChild(p);
					p.className = "error";
				}else{
					var results = transport.responseXML.getElementsByTagName("record");
					var state = form["state"].value;
					if(results.length>0){
						for(var i=0; i< results.length;i++){
							if(results[i].getAttribute("state")== state){
								var dealer_name = "";
								var address = "";
								var address2 = "";
								var city = "";
								var zip = "";
								var sales = "";
								var phone = "";
								if(results[i].getElementsByTagName("Dealer_Name").length>0 && results[i].getElementsByTagName("Dealer_Name")[0].firstChild){
									dealer_name = results[i].getElementsByTagName("Dealer_Name")[0].firstChild.nodeValue;
								}else if(results[i].getElementsByTagName("CompanyName").length>0 && results[i].getElementsByTagName("CompanyName")[0].firstChild){
									dealer_name = results[i].getElementsByTagName("CompanyName")[0].firstChild.nodeValue;
									if(results[i].getElementsByTagName("Text46").length>0 && results[i].getElementsByTagName("Text46")[0].firstChild){
											if(results[i].getElementsByTagName("Text46")[0].firstChild.nodeValue.toLowerCase() == 'yes'){
												dealer_name += " - QAP Certified";
											}
										}
								}
								if(results[i].getElementsByTagName("Address").length>0 && results[i].getElementsByTagName("Address")[0].firstChild){
									address = results[i].getElementsByTagName("Address")[0].firstChild.nodeValue;
								}
								if(results[i].getElementsByTagName("Address_2").length>0 && results[i].getElementsByTagName("Address_2")[0].firstChild){
									address2 = results[i].getElementsByTagName("Address_2")[0].firstChild.nodeValue;
								}
								if(results[i].getElementsByTagName("City").length>0 && results[i].getElementsByTagName("City")[0].firstChild){
									city = results[i].getElementsByTagName("City")[0].firstChild.nodeValue;
								}
								if(results[i].getElementsByTagName("Zip").length>0 && results[i].getElementsByTagName("Zip")[0].firstChild){
									zip = results[i].getElementsByTagName("Zip")[0].firstChild.nodeValue;
								}
								if(results[i].getElementsByTagName("Sales_Consultant").length>0 && results[i].getElementsByTagName("Sales_Consultant")[0].firstChild){
									sales = results[i].getElementsByTagName("Sales_Consultant")[0].firstChild.nodeValue;
								}else if(results[i].getElementsByTagName("RepFirstName").length>0 && results[i].getElementsByTagName("RepFirstName")[0].firstChild){
									sales = results[i].getElementsByTagName("RepFirstName")[0].firstChild.nodeValue + " " +results[i].getElementsByTagName("RepLastName")[0].firstChild.nodeValue;
								}
								
								if(results[i].getElementsByTagName("Dealer_Phone_Number").length>0 && results[i].getElementsByTagName("Dealer_Phone_Number")[0].firstChild){
									phone = results[i].getElementsByTagName("Dealer_Phone_Number")[0].firstChild.nodeValue;
								}else if(results[i].getElementsByTagName("Phone").length>0 && results[i].getElementsByTagName("Phone")[0].firstChild){
									phone = results[i].getElementsByTagName("Phone")[0].firstChild.nodeValue;
								}
								var dl = document.createElement("dl");
								var dt = document.createElement("dt");
								var dtv = dealer_name.toUpperCase();
								dt.appendChild(document.createTextNode(dtv));
								
								var dd1 = document.createElement("dd");
								if(address.trim() != ""){
									address += ", ";
								}
								if(address2.trim() != ""){
									address +=  address2 + ", ";
								}
								if(city.trim() != ""){
									city += ", ";
								}
								
								var ddv =  ParseSpecial(address.toLowerCase()) + city.toLowerCase() + state.toUpperCase()  + " " + zip;
								dd1.appendChild(document.createTextNode(ddv));
								
								/*	var span = document.createElement("span");
									span.appendChild(document.createTextNode(state));
									dd1.appendChild(document.createTextNode(address.toLowerCase() + ", " + city.toLowerCase() + ", "));
									dd1.appendChild(span);
									dd1.appendChild(document.createTextNode(" " + zip)); */
						
								var dd2 = document.createElement("dd");
								if(sales.trim() != ""){
									 ddv = sales;
									 if(phone.trim() != ""){
										 ddv += ": " +phone;
									 }
								 }
								else ddv = phone;
								dd2.appendChild(document.createTextNode(ParseSpecial(ddv.toLowerCase())));
								
								dl.appendChild(dt);
								dl.appendChild(dd1);
								dl.appendChild(dd2);
								$('results').appendChild(dl);
								found = true;
							}
						}
					}else {
							results = transport.responseXML.getElementsByTagName("ResultSet");
							for(var i=0; i< results.length;i++){
								var state_name = "";
								if(results[i].getElementsByTagName("p_state").length>0 && results[i].getElementsByTagName("p_state")[0].firstChild){
										state_name = results[i].getElementsByTagName("p_state")[0].firstChild.nodeValue;
									}
								if(state_name== state){
									var org_name = "";
									var address = "";
									var address2 = "";
									var city = "";
									
									var zip = "";
									var specialist = "";
									var phone = "";
									if(results[i].getElementsByTagName("p_name").length>0 && results[i].getElementsByTagName("p_name")[0].firstChild){
										org_name = results[i].getElementsByTagName("p_name")[0].firstChild.nodeValue;
										if(results[i].getElementsByTagName("Text46").length>0 && results[i].getElementsByTagName("Text46")[0].firstChild){
											if(results[i].getElementsByTagName("Text46")[0].firstChild.nodeValue.toLowerCase() == 'yes'){
												org_name += " - QAP Certified";
											}
										}
									}
									if(results[i].getElementsByTagName("p_address1").length>0 && results[i].getElementsByTagName("p_address1")[0].firstChild){
										address = results[i].getElementsByTagName("p_address1")[0].firstChild.nodeValue;
									}
									if(results[i].getElementsByTagName("p_address2").length>0 && results[i].getElementsByTagName("p_address2")[0].firstChild){
										address2 = results[i].getElementsByTagName("p_address2")[0].firstChild.nodeValue;
									}
									if(results[i].getElementsByTagName("p_city").length>0 && results[i].getElementsByTagName("p_city")[0].firstChild){
										city = results[i].getElementsByTagName("p_city")[0].firstChild.nodeValue;
									}
									
									if(results[i].getElementsByTagName("p_zip").length>0 && results[i].getElementsByTagName("p_zip")[0].firstChild){
										zip = results[i].getElementsByTagName("p_zip")[0].firstChild.nodeValue;
									}
									if(results[i].getElementsByTagName("c_firstname").length>0 && results[i].getElementsByTagName("c_firstname")[0].firstChild){
										specialist = results[i].getElementsByTagName("c_firstname")[0].firstChild.nodeValue 
									}
									if(results[i].getElementsByTagName("c_lastname").length>0 && results[i].getElementsByTagName("c_lastname")[0].firstChild){
										specialist = specialist + " "+ results[i].getElementsByTagName("c_lastname")[0].firstChild.nodeValue;
									}
								
									if(results[i].getElementsByTagName("c_phone").length>0 && results[i].getElementsByTagName("c_phone")[0].firstChild){
										phone = results[i].getElementsByTagName("c_phone")[0].firstChild.nodeValue;
									}
									var dl = document.createElement("dl");
									var dt = document.createElement("dt");
									var dtv = org_name.toUpperCase();
									dt.appendChild(document.createTextNode(dtv));
									
									var dd1 = document.createElement("dd");
									if(address.trim() != ""){
										address += ", ";
									}
									if(address2.trim() != ""){
										address +=  address2 + ", ";
									}
									if(city.trim() != ""){
										city += ", ";
									}
									
									var ddv =  address + city + state.toUpperCase()  + " " + zip;
									dd1.appendChild(document.createTextNode(ddv));
									
									var dd2 = document.createElement("dd");
									if(specialist.trim() != ""){
										 ddv = specialist;
										 if(phone.trim() != ""){
											 ddv += ": " +phone;
										 }
									 }
									else ddv = phone;
									
									dd2.appendChild(document.createTextNode(ddv));
									
									dl.appendChild(dt);
									dl.appendChild(dd1);
									dl.appendChild(dd2);
									$('results').appendChild(dl);
									found = true;
								}
						
						}
					
					}
					
					if(!found){
						var p = document.createElement("p");
						p.appendChild(document.createTextNode("No result found."));
						$('results').appendChild(p);
					}
				}
			}
			
		},
		on404: function(t) {
			 Firelog.log("Error 404: location " + xhr.statusText + " was not found.");
		},
		onFailure: function(t) {
			Firelog.log("Validate Method Error " + xhr.status + " -- " + xhr.statusText);
		}
	}

//	Event.stop(evt);
	new Ajax.Request(url, opt);
}


function ParseSpecial(s){
	//var replaceArray=new Array(\sNE\s\, \sNW[,|\s]\, \s\SE[,|\s]\, \sSW[,|\s]\, \sUS[,|\s]\, \RR\d(1)\, \sFM[,|\s]\);
	//var replaceArray=new Array(" NE ", " NW ", " SE ", " SW ", " US ", "RR", " FM ");
	var replaceArray={};
	replaceArray[" PO "]=/\sPO\s/;
	replaceArray[" RL "]=/\sRL\s/;
	replaceArray[" NE"]=/\sNE(,|\s)/;
	replaceArray[" NW"]=/\sNW(,|\s)/;
	replaceArray[" SE"]=/\sSE(,|\s)/;
	replaceArray[" SW"]=/\sSW(,|\s)/;
	replaceArray[" US"]=/\sUS(,|\s)/;
	replaceArray["RR"]=/RR\d{1}/;
	replaceArray[" FM"]=/\sFM(,|\s)/;
	replaceArray["AJ"]=/^AJ(,|\s)/;
	
	for(i in replaceArray){
		if(replaceArray[i].test(s.toUpperCase())){
			s = s.replace(i.toLowerCase(), i);
		}
		if(s.toUpperCase().endsWith(i) && i.startsWith(" ")){
			s=s.substring(0,s.length-i.length)+i;
		}
	}
	
	s = s.replace(/\.\w\./g, function(match){
        return "."+match.charAt(1).toUpperCase()+"."; 
    });
	return s;
}



function initShadowAction(evt){
	if(evt.action){
		var form = evt;
	}else{
		Event.stop(evt);
		var form = Event.findElement(evt, 'form');
	}
	var url = form.action+"results/";
	var pars = Form.serialize(form);
	var link = document.createElement("a");
	link.href=url+"?"+pars;
	link.rel="shadowbox;width=690;height=489;"

	 var options = {
        resizeLgImages: true,
		handleLgImages: "none",
		skipSetup:true,
        displayNav: true,
        overlayBgImage: "",
        loadingImage: "../images/gui/loading.gif",
		onOpen:function(){
			
		},
		onClose: function(){
			
		},
		onFinish: function(){
			
		
		}
    };

    Shadowbox.init(options);
	Shadowbox.open(link);
}

function init(){
	if ($('tabs')) { new Fabtabs('tabs'); }
	if ($('toolkit-tabs')) { new Fabtabs('toolkit-tabs'); }	
	if ($('test-accordion')) { loadAccordions(); }	
	if ($('reimbursementswf') || $('onstarswf')) { initFlvPlayer(); }
	if ($$('a[rel~="external"]')) { openExternal(); }
	relPopups();	
}

Event.observe(window,'load',function(){ init(); },false);
Event.observe(window, 'load', initSaf );
Event.observe(window, 'load', submitbutton );

Element.addMethods({
	removeAllChildren: function(element) {
      for(var i=element.childNodes.length; i>0; i--){
      		element.removeChild(element.childNodes[i-1]);
      }
      return;
    }
	
});

function initshadowBox(){	
	Shadowbox.init();
}

document.observe("dom:loaded", function() {
	initshadowBox();
});


Event.observe(window, 'load', function(){
		if ($('request-app')) { new Validation('request-app', {immediate : true});	}	
},false);



function addBookmark(evt){
	var link = Event.findElement(evt, 'a');
	Event.stop(evt);
	if(window.sidebar && window.sidebar.addPanel){
		window.sidebar.addPanel(link.title,link.href,'');
	}else {
		addBookmarkObj.exec(link.href,link.title);
	}
}

Event.observe(window, 'load', function(){
		$$('a[rel~="add-bookmark"]').each(function(item){
			Event.observe(item,'click',addBookmark,false);
		});
},false);

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };