// JavaScript Document

//***************************************************************************************************
//***************************************************************************************************
//***************************************************************************************************
//MSD
function countySearch(form, theCounty) 
{
	if(theCounty == "- Select A County -" || theCounty == "- Select County -" ) 
	{
		alert ("Please select a County.");
		return;
	}
	XRL = "http://www.legis.state.pa.us/cfdocs/legis/home/findyourlegislator/county_list.cfm?CNTYLIST=" + theCounty;
	openWinLarge(XRL);
	return;
}

//***************************************************************************************************
//***************************************************************************************************
//***************************************************************************************************

function openWin(URL) 
{ 
	scr_res = screen.width;
	if(scr_res == "640") 
	{ aWindow = window.open(URL, "thewindow","height=270,width=350,left=120,top=100,toolbar=no,scrollbars=no,menubar=no"); }
	else if(scr_res == "800") 
	{ aWindow = window.open(URL, "thewindow","height=370,width=350,left=210,top=110,toolbar=no,scrollbars=no,menubar=no"); }
	else if(scr_res == "1024") 
	{ aWindow = window.open(URL, "thewindow","height=390,width=350,left=310,top=110,toolbar=no,scrollbars=no,menubar=no"); }
	else 
	{ aWindow = window.open(URL, "thewindow","height=370,width=350,left=100,top=130,toolbar=no,scrollbars=no,menubar=no"); }
}

function openWinLarge(URL) 
{ 
	scr_res = screen.width;
	aWindow = window.open(URL, "thewindow","height=768,width=1024,left=100,top=130,toolbar=no,scrollbars=yes,menubar=yes");
}


// this runs at body.onLoad();
function initJS() {
	//runGoogleAds();
	//include_dom();//runGoogleAd1();
	//runGoogleAd2();
	checkNifty();
}

function include_dom() {
    var html_doc = $('ads_side_content');
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', "http://pagead2.googlesyndication.com/pagead/show_ads.js");
    html_doc.appendChild(js);
    return false;
}

// This function rounds all the corners that need to be rounded
function checkNifty() {
	if(!NiftyCheck()) {	
		return;
	}	
	Rounded('div.newspost_main','all','#FFFFFF','#DDDDFF', 'smooth border #FF0000');
	Rounded('div.campaign_main','all','#FFFFFF','#FFFFFF', 'smooth border #FF0000');
	
	Rounded('div.content_block_full','all','#888899','#DDDDFF', 'smooth');
	
	Rounded('div.content_block_main','top','#FFFFFF','#DDDDFF', 'smooth border #FF0000');
	Rounded('div.content_block_main','bottom','#FFFFFF','#FFFFFF', 'smooth border #FF0000');
	
	Rounded('div.sidediv','tr','#888899','#000066', 'smooth');
	Rounded('div.sidediv','br','#888899','#DDDDFF', 'smooth');
	Rounded('div#ads_side_content','tr br','#888899','#DDDDFF', 'smooth');
	
	Rounded('div#mainimage','br','#888899','#000066', 'smooth');
	Rounded('div#footer','tr','#888899','#DDDDFF', 'smooth');
	
	Rounded('div.round_noborder','top','#888899','#000066', 'smooth');
	Rounded('div.round_noborder','bottom','#888899','#FFFFFF', 'smooth');
	
	Rounded('div.external_links_section','all','#FFFFFF','#DDDDFF', 'smooth border #FF0000');
}


function setInit() {
	var position = findPos($('navbar'));
	$('volunteer').style.top = position[1] + $('navbar').offsetHeight - 4 + "px";
	return true;
}

function showSenate() {
	// Change this to use PROTOTYPE.js
	$('senatordiv').style.display = "block";
	$('congressmandiv').style.display = "none";
	$('OfficialTypeType').value = "senate";
	return true;
}

function showHouse() {
	// Change this to use PROTOTYPE.js
	$('congressmandiv').style.display = "block";
	$('senatordiv').style.display = "none";
	$('OfficialTypeType').value = "house";
	return true;
}

function toggleDiv(div, force_closed) {
	if (force_closed === null) {
		force_closed = false;
	}
	if (force_closed == true) {
		$(div).style.display = "none";
	}
	else {
		if ($(div).style.display == "none") {
			$(div).style.display = "block";
		}
		else {
			$(div).style.display = "none";
		}
	}
}

/**
 * Sends an AJAX request
 *
 * @param		
 */
function getAlbumPage(album_id) {
	var new_URL = "ajax_view_album/";
	new Ajax.Updater('response',
				 new_URL, 
				 {
				  asynchronous:true, 
				  evalScripts:true,
				  parameters:'g_id='+album_id, // Below loader generated at http://www.ajaxload.info/
				  onLoading: function() { Element.update('loader', '<div style="text-align:center"><img src="/img/ajax-loader.gif"></div>'); },
				  onSuccess:function() { Element.update('loader', '');}
				 }
	);
	
}

function changeImage(img_id, img_name) {	
	$('gal_img').src = 'http://www.phillynorml.org/gallery/d/'+img_id+'/'+img_name;
}

function submitDonateFrm(event, donate_amt) {
	// FIX THIS
	/*document.frmPayPalDonate.target = "_blank";
	document.frmPayPalDonate.action = "https://www.paypal.com/cgi-bin/webscr";
	*/
	$('PhillynormlMemberDonation').value = donate_amt;
	var thisrt_size = $('TeeshirtSize');
	if (donate_amt >= 35 && thisrt_size.selectedIndex == 0) {
		alert('Please select a t-shirt size before proceeding.');
		event.stop();
	}
	else {
		document.donatefrm.submit();
	}
}

function submitSponsorDonateFrm(event, donate_amt) {
	$('PhillynormlMemberDonation').value = donate_amt;
	//document.donatefrm.submit();
}

function changeDonateLevel() {
	if ($('a3')) {
		if ($('a3').value == 5) {
			Element.show('donate_amt_l1');
			Element.hide('donate_amt_l2');
			Element.hide('donate_amt_l3');
			Element.hide('donate_amt_l4');
		}
		else if ($('a3').value == 10) {
			Element.hide('donate_amt_l1');
			Element.show('donate_amt_l2');
			Element.hide('donate_amt_l3');
			Element.hide('donate_amt_l4');
		}
		else if ($('a3').value == 25) {
			Element.hide('donate_amt_l1');		
			Element.hide('donate_amt_l2');
			Element.show('donate_amt_l3');
			Element.hide('donate_amt_l4');
		}
		else if ($('a3').value >= 35) {
			Element.hide('donate_amt_l1');
			Element.hide('donate_amt_l2');
			Element.hide('donate_amt_l3');
			Element.show('donate_amt_l4');
		}
		if ($('PhillynormlMemberDonation')) {
			$('PhillynormlMemberDonation').value = $('a3').value;
		}
	}
	else if ($('amount')) {
		if ($('PhillynormlMemberDonation')) {
			$('PhillynormlMemberDonation').value = $('amount').value;
		}
	}
	
}


/**
* Highlight the parent row of a given error message <div> tag
*
* @param        string        strID        ID of the element of whos parent to highlight
* @param        integer        iLimit        Maximum number of levels to traverse up
* @return        boolean                    True on success, false on error
*/
function highLightRow(strID, iLimit) {
	if ( ! $(strID) ) { return false; }
	var objDiv = $(strID);
	var objParent = objDiv.parentNode;
	var iControll = 0;
	if (iLimit == null) {
		iLimit = 5;
	}
	// Loop up until we find the parent <tr> or iControll goes over iLimit
	while( objParent.tagName != 'TR' || iControll >= iLimit) {
		objParent = objParent.parentNode;
		iControll++;
	}
	
	// Error highlight all the <td>s in this row
	for(var i=0;i<objParent.childNodes.length;++i) {
		if (objParent.childNodes[i].tagName == 'TD' && Element.hasClassName(objParent.childNodes[i], 'fields') ) {
			Element.addClassName(objParent.childNodes[i], 'error_message');
			Element.removeClassName(objParent.childNodes[i], 'fields');
		}
		else if (objParent.childNodes[i].tagName == 'TD' && Element.hasClassName(objParent.childNodes[i], 'signup_field') ) {
			Element.addClassName(objParent.childNodes[i], 'error_message_sf');
			Element.removeClassName(objParent.childNodes[i], 'signup_field');
		}
		else if (objParent.childNodes[i].tagName == 'TD' && Element.hasClassName(objParent.childNodes[i], 'signup_field_column') ) {
			Element.addClassName(objParent.childNodes[i], 'error_message_sf_nsb');
			Element.removeClassName(objParent.childNodes[i], 'signup_field_column');
		}
	}
}

/**
* UnHighlight the parent row of a given error message <div> tag
*
* @param        string        strID        ID of the element of whos parent to be unhighlighted
* @param        integer        iLimit        Maximum number of levels to traverse up
* @return        boolean                    True on success, false on error
*/
function unhighLightRow(strID, iLimit) {
	if ( ! $(strID) ) { return false; }
	var objDiv = $(strID);
	var objParent = objDiv.parentNode;
	var iControll = 0;
	if (iLimit == null) {
		iLimit = 5;
	}
	// Loop up until we find the parent <tr> or iControll goes over iLimit
	while( objParent.tagName != 'TR' || iControll >= iLimit) {
		objParent = objParent.parentNode;
		iControll++;
	}
	
	// Error highlight all the <td>s in this row
	for(var i=0;i<objParent.childNodes.length;++i) {
		if (objParent.childNodes[i].tagName == 'TD' &&
			Element.hasClassName(objParent.childNodes[i], 'error_message') ) {
			Element.removeClassName(objParent.childNodes[i], 'error_message');
			Element.addClassName(objParent.childNodes[i], 'fields');
		}
		else if (objParent.childNodes[i].tagName == 'TD' &&
			Element.hasClassName(objParent.childNodes[i], 'error_message_sf') ) {
			Element.removeClassName(objParent.childNodes[i], 'error_message_sf');
			Element.addClassName(objParent.childNodes[i], 'signup_field');
		}
		else if (objParent.childNodes[i].tagName == 'TD' &&
			Element.hasClassName(objParent.childNodes[i], 'error_message_sf_nsb') ) {
			Element.removeClassName(objParent.childNodes[i], 'error_message_sf_nsb');
			Element.addClassName(objParent.childNodes[i], 'signup_field_column');
		}
	}
}

function setCaptchaField(form_id, controller) {
	//alert('ch field: ' + Recaptcha.$('recaptcha_challenge_field').value);
	$(controller+'RecaptchaChallengeField').value = Recaptcha.$('recaptcha_challenge_field').value;
	$(controller+'RecaptchaResponseField').value = Recaptcha.$('recaptcha_response_field').value;
}

function getElectedOfficialsByType(rep_type, sort_string) {
	var new_URL = "/involve/ajax_get_legislator_info_for_rep_type/"+rep_type;
	if (sort_string != null && sort_string != "") {
		new_URL += sort_string;
	}
	new Ajax.Updater('response',
					 new_URL, {
						asynchronous:true,
						evalScripts:true,
						onLoading: function() {
							Element.update('div_list_elected_officials', '<div style="text-align:center">Loading Elected Officials List, please wait...<br /><img src="/img/ajax-loader.gif"></div>');
						},
						onSuccess:function(transport) {
							var new_rep_info = '';
							if (transport.responseText) {
								new_rep_info = transport.responseText;
							}
							Element.update('div_list_elected_officials', new_rep_info);
						}
					});
}

function getElectedOfficialsByZipCode(obj_element) {
	var zip5_el = null;
	var zip4_el = null;
	var voltype = null;
	if (obj_element.id.match('PhillynormlMember')) {
		zip5_el = $('PhillynormlMemberZip5');
		zip4_el = $('PhillynormlMemberZip4');
	}
	else if (obj_element.id.match('Pa4mmjVolunteer')) {
		zip5_el = $('Pa4mmjVolunteerZip');
		zip4_el = $('Pa4mmjVolunteerZip4');
	}
	var zip5 = zip5_el.value;
	var zip4 = zip4_el.value;
	var error_td = null;
	
	var valid_zip5 = true;
	var valid_zip4 = true;
	
	if (zip5.length != 5) {
		valid_zip5 = false;
		zip5_el.up().removeClassName('signup_field').up().next().down().removeClassName('signup_field');
		zip5_el.up().addClassName('error_message_sf_ntb').up().next().down().addClassName('error_message_sf');
		error_td = zip5_el.up().up().next().down();
		if (error_td.down() && error_td.down().id.match(/ErrorDiv_/)) {
			error_td.down().style.display = "block";
			if (zip5.length == 0) {
				error_td.down().innerHTML = "ZIP5 is required";
			}
			else {
				error_td.down().innerHTML = "ZIP5 must be 5 digits";
			}
		}
		else {
			var js = document.createElement('div');
			js.setAttribute('id', 'ErrorDiv_'+zip5_el.id);
			if (zip5.length == 0) {
				js.innerHTML = "ZIP5 is required";
			}
			else {
				js.innerHTML = "ZIP5 must be 5 digits";
			}
			error_td.appendChild(js);
		}
	}
	else {
		valid_zip5 = true;
		zip5_el.up().removeClassName('error_message_sf_ntb').up().next().down().removeClassName('error_message_sf');
		zip5_el.up().addClassName('signup_field').up().next().down().addClassName('signup_field');
		if (zip4.length != 0 && zip4.length != 4) {
			valid_zip4 = false;
			zip4_el.up().removeClassName('signup_field').up().next().down().removeClassName('signup_field');
			zip4_el.up().addClassName('error_message_sf_ntb').up().next().down().addClassName('error_message_sf');
			error_td = zip5_el.up().up().next().down();
			if (error_td.down() && error_td.down().id.match(/ErrorDiv_/)) {
				error_td.down().style.display = "block";
				error_td.down().innerHTML = "ZIP4 must be 4 digits";
			}
			else {
				var js = document.createElement('div');
				js.setAttribute('id', 'ErrorDiv_'+zip4_el.id);
				js.innerHTML = "ZIP4 must be 4 digits";
				error_td.appendChild(js);
			}
		}
		else {
			valid_zip4 = true;
			error_td = zip5_el.up().up().next().down();
			if (error_td.down() && error_td.down().id.match(/ErrorDiv_/)) {
				error_td.down().style.display = "none";
			}
		}
	}
	
	if (valid_zip5 && valid_zip4) {
		// Ok now get the legislators' information via AJAX for the user to see. We'll do this again when
		// the user submits their data so we don't have to pass it back to Cake, its just for the user's
		// immediate information.
		var new_URL = "/involve/ajax_get_legislator_info_for_zip_code/"+$('CampaignCampaignTypeId').value+"/"+zip5+"/"+zip4;
		new Ajax.Updater('response',
						new_URL, {
							asynchronous:true,
							evalScripts:true,
							onLoading: function() { Element.update('zip_selected_rep_list', '<div style="text-align:center"><img src="/img/ajax-loader.gif"></div>'); },
							onSuccess:function(transport) {
								var new_rep_info = '';
								if (transport.responseText) {
									new_rep_info = transport.responseText;
								}
								Element.update('zip_selected_rep_list', new_rep_info);
							}
						});
		//alert('Valid ZIP code!\n' + zip5 + '-' + zip4);
	}
	
}
