//radio two common JS modules

// ad zone
advertising_zone = 'radio'; 

//G-jump menu

function r2jumpMenu(){
var target=document.getElementById("progJump");

//	window.location= "?"+ target;
	
var where ="?"+ document.forms[1].jump.options[document.getElementById('jump').selectedIndex].value;
		//var where ="?"+ target.jump.options.selectedIndex.value;
//	alert('methinks i am: '+where)
	window.location= where;
	
}

function scheduleRegion(){
var target=document.getElementById("skedJump");

//	window.location= "?"+ target;
	
var where ="?"+ document.forms['skedJump'].region.options[document.getElementById('region').selectedIndex].value;
		//var where ="?"+ target.jump.options.selectedIndex.value;
//	alert('methinks i am: '+where)
	window.location= where;
	
}

function concertsGenre(){
var target=document.getElementById("genreJump");

//	window.location= "?"+ target;
	
var where ="?"+ document.forms['genreJump'].genre.options[document.getElementById('genre').selectedIndex].value;
		//var where ="?"+ target.jump.options.selectedIndex.value;
//	alert('methinks i am: '+where)
	window.location= where;
	
}
function concertsArtist(){
var target=document.getElementById("artistJump");

//	window.location= "?"+ target;
	
var where ="?"+ document.forms['artistJump'].artist.options[document.getElementById('artist').selectedIndex].value;
		//var where ="?"+ target.jump.options.selectedIndex.value;
//	alert('methinks i am: '+where)
	window.location= where;
	
}

function concertsEvents(){
var target=document.getElementById("eventJump");

//	window.location= "?"+ target;
	
var where ="?"+ document.forms['eventJump'].eventName.options[document.getElementById('eventName').selectedIndex].value;
		//var where ="?"+ target.jump.options.selectedIndex.value;
//	alert('methinks i am: '+where)
	window.location= where;
	
}

//NEW DRAWER SYSTEM - no need to set NUMEBR OF DRAWERS
	var openedImage = "<img src=\"images/icons/nav_closed.gif\" border=\"0\" alt=\"collapse\"/>";
	var closedImage = "<img src=\"images/icons/nav_opened.gif\" border=\"0\" alt=\"expand\"/>";
	//added drawer finder
	function countDrawers(){
	var inc=0;
	var alltags=document.all? document.all : document.getElementsByTagName("*");
//	customcollection=new Array[];
	var count=0;
	for (i=0; i<alltags.length; i++){
	if (alltags[i].className=="drawer odd" || alltags[i].className=="drawer even"){
		//customcollection[inc++]=alltags[i]
		count = count +1;
		}
	
	}
	//var x = customcollection[0];
	//alert("I thnik there are"+count+"drawers");
	return count;
	}
	
	
	//DRAWER MANAGEMENT HOME COOKED BY ROS!
	function setDrawers(){
		
	//alert("setting drawers");
 numDrawers = countDrawers();
	window.numDrawers = numDrawers;
	//alert("setting"+numDrawers+ "drawers");
		for (a=1;a<=numDrawers;a++){
		var division = 'drawer'+a;
		var marker = 'marker'+a;
		document.getElementById(division).style.display ='none';
		document.getElementById(marker).className='closed';
		var imageSlot=document.getElementById(marker).getElementsByTagName("A");
		imageSlot[0].innerHTML=closedImage;
		}
	}
	function openAll(){
	//alert("opening drawers"+window.numDrawers);
		for (a=1;a<=window.numDrawers;a++){
		var division = 'drawer'+a;
		var statusDiv='marker'+a;
		document.getElementById(division).style.display ='block';
		document.getElementById(statusDiv).className = 'opened';
		var imageSlot=document.getElementById(statusDiv).getElementsByTagName("A");
		imageSlot[0].innerHTML=openedImage;
		}
		
	}
	function closeAll(){
	//alert("opening drawers"+window.numDrawers);
		for (a=1;a<=window.numDrawers;a++){
		var division = 'drawer'+a;
		var statusDiv='marker'+a;
		document.getElementById(division).style.display ='none';
		document.getElementById(statusDiv).className = 'closed';
		var imageSlot=document.getElementById(statusDiv).getElementsByTagName("A");
		imageSlot[0].innerHTML=closedImage;
		}
		
	}
	function expandCollapse (divName, markerName){
			var target=document.getElementById(divName);
			var statusDiv=document.getElementById(markerName);	
			if (target.style.display == 'block'){
			target.style.display = 'none';
			statusDiv.className = 'closed';
			//statusDiv.style.display = 'none';
			var imageSlot=document.getElementById(markerName).getElementsByTagName("A");
		imageSlot[0].innerHTML=closedImage;
			}
			else {
			statusDiv.className = 'opened';
			target.style.display = 'block';
			var imageSlot=document.getElementById(markerName).getElementsByTagName("A");
		imageSlot[0].innerHTML=openedImage;
			}
			
	}
	
//AJAX PLAYLIST FINDER

	    function makeRequest(url) {
	        var http_request = false;

	        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	            http_request = new XMLHttpRequest();
	            if (http_request.overrideMimeType) {
	                http_request.overrideMimeType('text/xml');
	                // See note below about this line
	            }
	        } else if (window.ActiveXObject) { // IE
	            try {
	                http_request = new ActiveXObject("Msxml2.XMLHTTP");
	            } catch (e) {
	                try {
	                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
	                } catch (e) {}
	            }
	        }

	        if (!http_request) {
	            alert('Giving up :( Cannot create an XMLHTTP instance');
	            return false;
	        }
	        http_request.onreadystatechange = function() { alertContents(http_request, url); };
	        http_request.open('HEAD', url, true);
	        http_request.send(null);

	    }

	    function alertContents(http_request, url) {

	        if (http_request.readyState == 4) {
	            if (http_request.status == 200) {
	                //alert(http_request.responseText);
					//document.write(http_request.responseText);
					//document.getElementById("freqbox").innerHTML=http_request.responseText;
				//	tack on the string and go!!
		//	feedBack('Valid Palylist.');
		//go to URL
	getPlaylist(url);
	            } else {
	             	
			//alert('Sorry, that playlist does not appear to be on file.');
	feedBack('Sorry, that playlist is not on file.');  
	            }
	        }

	    }
//GO TO PLAYLIST PAGE BASED ONCE IT IS VALID
	function getPlaylist(url){
	//	alert("getting"+url);
		if(url.match("daily")){
			//alert("a daily!");
			prefix="/radio2/playlists.html";
		}
		else {
		//	alert("a single!");
		prefix="/radio2/singlePlaylist.html";
		}
			window.location = prefix+'?'+url;
		
		
	}

function playlistDateSlug ()
{
	
	var months = ["January","February", "March", "April", "May", "June", "July", "August" , "September", "October" , "November" , "December"];
	var days = ["Sunday","Monday", "Tuesday" , "Wednesday", "Thursday", "Friday", "Saturday"];

	var rawSlug ="";
	var extractedDate ="";
	var year ="";
	var month="";
	var day="";
	var x ="";
	var datDay="";
	var datMonth="";
	
	if( window.location.search.substr(1) !== '' )
	{
		rawSLug = window.location.search.substr(1);
		extractedDate = rawSLug.split('/');
		fullPL = extractedDate[5];
		plSHOW = fullPL.split('-');
		plSHOW = plSHOW[1];
		plDATE = plSHOW.split('.');
		plDATE = plDATE[0];
		//plSHOW3 = plSHOW2[0];
		show = extractedDate[4];
		extractedDate = plDATE;
		// ofextractedDate e.g. 20081206
		year = Number( extractedDate.substr(0,4) );//wAS SUBSTR
		month = Number(extractedDate.substr(4,2) )-1 ;//wAS SUBSTR
		day = Number( extractedDate.substr(6,2) );//wAS SUBSTR
		pastDate=new Date();
		pastDate.setFullYear(year, month, day);
		//alert('think date is'+year + month + day);
		//alert("x");
		//feedBack('Playlist for: ' + convertThis);
		focusDropDowns(pastDate.getFullYear(), pastDate.getMonth(), pastDate.getDate(), show);
		feedBack('Playlist for: ' + months[pastDate.getMonth()]+' '+ pastDate.getDate()+', '+ pastDate.getFullYear());
	}
	else
	{
		datum = new Date();
		//	document.getElementById('playlistSlug').innerHTML ="no query";
		x=2;
		feedBack('Playlist for: '+ days[datum.getDay()] + ' '+ months[datum.getMonth()]+' '+ datum.getDate()+', '+ datum.getFullYear());
		focusDropDowns(datum.getFullYear(), datum.getMonth(), datum.getDate() );
	}
}

function setOptionElementToNumber ( value, element )
{
	var i = element.options.length;
	while( i-- )
	{
		if( Number(element.options[ i ].value) == value ) 
		{ 
			element.options.selectedIndex = i;
			return true;
		}
	}
	return false
}

function focusDropDowns(year, month, date, show)
{
	//set the DDs to their correct index based on the given date 
	//month DD
	var monthElement = document.getElementById('month');
	var dateElement = document.getElementById('day');
	var yearElement = document.getElementById('year');
	
	setOptionElementToNumber( date, dateElement );
	setOptionElementToNumber( month+1, monthElement );
	setOptionElementToNumber( year, yearElement );

	//Not sure what this does???
	var showBox = document.getElementById('showName');
	
	for (a=0; a < showBox.options.length; a++)
	{
		if(showBox.options[a].value === show)
		{
			showBox.options.selectedIndex = a;
		}
	}
	
}

function feedBack(message){
	document.getElementById("r2Message").innerHTML= message;
	
}


	
				
						function cityRequest(){

									var showName = document.freq.showName.options[document.freq.showName.selectedIndex].value;
									var year = document.freq.year.options[document.freq.year.selectedIndex].value;
									var monthDay = document.freq.month.options[document.freq.month.selectedIndex].value;
									var day = document.freq.day.options[document.freq.day.selectedIndex].value;	
									var wtf = "/radio2/includes/playlists/"+showName+'/'+showName+'-'+year+monthDay+day+'.html';
				
							makeRequest(wtf);
									
										}
										
										//AjaxValidateSubmit built by Klepl
										var ajaxValidateSubmit = function() {
	
	var _form;
	var _fields;
	var _errorDiv;
	var _normalClass;
	var _errorClass;
	var _errorImage;
	var _successMsg;
	var _failureMsg;
	var _debugMode;
	
	var _submitUrl;		
	var _postData;
	var _errors;


	return {
		init : function(form, params) {
			_form = form;
			_fields = params.fields;
			_normalClass = params.normalClass;
			_errorClass = params.errorClass;
			_errorImage = params.errorImage;
			_successMsg = params.successMsg;
			if (params.failureMsg) {
				_failureMsg = params.failureMsg;
			} else {
				_failureMsg = params.successMsg;
			}
			_submitUrl = _form.getAttribute('action');
			_errorDiv = document.getElementById(params.errorDiv);
			_debugMode = params.debugMode;
			validateAndSubmit();
		}
	};
		
		
	function validateAndSubmit() {
		if (_debugMode) console.log('Validating fields');
		
		vAlert(0, '');
		vResetFieldClasses();
		_errors = false;
		_postData = "";
		
		if(document.getElementById) {
			for (var i=0; i<_fields.length; i++) {
				switch (_fields[i].type) {
					case 'hidden':
						var textFieldElem = document.getElementById(_fields[i].id);
						_postData += textFieldElem.name + '=' + encodeURIComponent(textFieldElem.value);
						break;
					case 'text':
						var textFieldElem = document.getElementById(_fields[i].id);
						switch (_fields[i].validate) {
							case 'notempty':
								if (textFieldElem.value == '') {
									_errors = true;
									textFieldElem.focus();
									vHighlightErrors(textFieldElem, _errorClass);
									vAlert(1, _fields[i].error, true);
								}
								break;
							case 'email':
								if (!validate_email(textFieldElem.value)) {
									_errors = true;
									textFieldElem.focus();
									vHighlightErrors(textFieldElem, _errorClass);
									vAlert(1, _fields[i].error, true);
								}
								break;
						}
						_postData += textFieldElem.name + '=' + encodeURIComponent(textFieldElem.value);
						break;
					case 'radio':
						var checkedOption = validate_radio(_fields[i].name);
						switch (_fields[i].validate) {
							case 'checked':
								if (!checkedOption) {
									_errors = true;
									vAlert(1, _fields[i].error, true);
								}
								break;
						}
						_postData += _fields[i].name + '=' + checkedOption;
						break;
					case 'checkbox':
						var checkBoxElem = document.getElementById(_fields[i].id);
						switch (_fields[i].validate) {
							case 'checked':
								if (!checkBoxElem.checked) {
									_errors = true;
									checkBoxElem.focus();
									vHighlightErrors(checkBoxElem, _errorClass);
									vAlert(1, _fields[i].error, true);
								}
								break;
						}
						_postData += checkBoxElem.name + '=' + checkBoxElem.value;
						break;
				}
				if (i < _fields.length-1) _postData += '&';
				if (_errors) break;
			}
			
			if (!_errors) doSubmit();
			return false;
			
		} else {
			return true; //continue and use server side
		}
	}
	
	
	function doSubmit() {
		var handleSuccess = function(o) {
			if(o.responseText !== undefined) {
				if (_debugMode) {
					vAlert(1, o.responseText);
				} else {
					vAlert(1, _successMsg);
				}
				vClearFields();
			}
			return false;					
		}
		var handleFailure = function(o) {
			if (_debugMode) {
				vAlert(1, o.responseText);
			} else {
				vAlert(1, _failureMsg);
			}
			vClearFields();
			return false;
		}				
		var callback =
		{
		  success:handleSuccess,
		  failure:handleFailure
		};
		vAlert(1, 'Sending...');
		if (_debugMode) console.log('Posting to: ' + _submitUrl);
		if (_debugMode) console.log('Post Data: ' + _postData);
		var request = YAHOO.util.Connect.asyncRequest('POST', _submitUrl, callback, _postData);
	}
	
	
	function validate_email(str) {
		if (str.indexOf('@') < 0 || str.indexOf('.') < 0 || str.lastIndexOf('.') < str.indexOf('@') || str.lastIndexOf('@') != str.indexOf('@')) {
			return false;
		}
		return true;
	}
	
	
	function validate_radio(radioName) {
		var radioArray = _form[radioName];
		for (var i=0; i<radioArray.length; i++) {
			if (radioArray[i].checked) {
				return radioArray[i].value;
			}
		}
		return false;
	}
	
	
	function vHighlightErrors(elem) {
		elem.className += (" "+_errorClass);
	}
	
	
	function vAlert(visible, message, showImage) {
		if (_errorDiv) {
			if (visible == 1) {
				if (showImage) {
					_errorDiv.innerHTML = '<p><img src="' + _errorImage + '" /> ' + message + '</p>';
				} else {
					_errorDiv.innerHTML = '<p>' + message + '</p>';
				}
				_errorDiv.style.display = 'block';
			} else {
				_errorDiv.innerHTML = message;
				_errorDiv.style.display = 'none';
			}
		}
	}
	
	
	function vClearFields() {
		for (var i=0; i<_fields.length; i++) {
			switch (_fields[i].type) {
				case 'text':
					var textFieldElem = document.getElementById(_fields[i].id);
					textFieldElem.value = '';
					break;
				case 'radio':
					var radioArray = _form[_fields[i].name];
					for (var j=0; j<radioArray.length; j++) {
						if (radioArray[j].checked) {
							radioArray[j].checked = false;
						}
					}
					break;
				case 'checkbox':
					var checkBoxElem = document.getElementById(_fields[i].id);
					checkBoxElem.checked = false;
					break;
			}
		}
	}
	
	function vResetFieldClasses() {
		for (var i=0; i<_fields.length; i++) {
			switch (_fields[i].type) {
				case 'text':
					var textFieldElem = document.getElementById(_fields[i].id);
					textFieldElem.className = _normalClass;
					break;
				case 'checkbox':
					var checkBoxElem = document.getElementById(_fields[i].id);
					checkBoxElem.className = '';
					break;
			}
		}
	}
		
		
		

}();

