// Unclaim the "$" namespace
jQuery.noConflict();
var $j = jQuery;

/**
 * page() is used in the pagination of the background and icon pages
 */
function page(pg) {

	// Maintain icon selections
	//checkIconSelection();

	document.getElementById('p').value = pg;
	document.ticker_sort.submit();
}

function getFlickr(page) {

	if (!page) {
		page = 1;
	}

	var flickr_box = document.getElementById("flickrbox");

	// Loading message
	flickr_box.innerHTML = "Retrieving Flickr Photos...";

	// Get the comments
	url = '/create/get_flickr_photos.php?fp=' + page;
	xmlhttp.open("GET", url ,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			flickr_box.innerHTML = xmlhttp.responseText;
		}
	}

	xmlhttp.send(null)
}

function use(image_url) {
	document.getElementById('flckr').src = image_url;
	document.getElementById('flickr_image').value = image_url;
	document.getElementById('selectedphotodiv').style.display = 'block';
}

function clearSelection() {
	document.getElementById('flckr').src = '';
	document.getElementById('flickr_image').value = '';
	document.getElementById('selectedphotodiv').style.display = 'none';
}

// saveIconSelection: Used to send the final icon selections from step 2 to step 3
function saveIconSelection() {
	// Write the current selection of icons to the 'icon' value of the main ticker form
	$j("#icon").attr('value', $j("#selectedicons").attr("value"));
}





////////////////////////////////////////////////// DATE FUNCTIONS
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
	
    // All characters are numbers.
    return true;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   
   return this;
}

function isDate(theDay, theMonth, theYear) {
	var daysInMonth	= DaysArray(12);
	
	// Dates
	var strDay		= theDay;
	var strMonth	= theMonth;
	var strYear		= theYear;
	
	// Make in to integers
	month	= parseInt(strMonth);
	day		= parseInt(strDay);
	year	= parseInt(strYear);
	
	if (strMonth.length < 1 || month < 1 || month > 12){
		return false
	
	} else if (day.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	
	} else {
		return true;
	}
}
////////////////////////////////////////////////// DATE FUNCTIONS





// Verify an email address
function valEmail(theEmail) {
	with (theEmail) {
		apos	= theEmail.indexOf("@");
		dotpos	= theEmail.lastIndexOf(".");
		
		if (apos < 1 || dotpos - apos < 2) {
			return false;
		} else {
			return true;
		}
	}
}

function valExist(theVal) {
	if ( typeof(theVal) == "undefined" ) {
		return false;
		
	} else {
		return true;
	}
}

// Verify the form
function verifyForm(form) {
	// Loop through form elements
	var errNum	= 0;
	var errMsg	= "";
	
	// TTC Additions
	var checkFDoC	= false;
		var FDoC_d	= '';
		var FDoC_m	= '';
		var FDoC_y	= '';
		
	var checkDoCE	= false;
		var DoCE_d	= '';
		var DoCE_m	= '';
		var DoCE_y	= '';
		
	var checkPoS	= false;
		var PoS_d	= '';
		var PoS_m	= '';
		var PoS_y	= '';
	
	for (var i= 0; i < form.elements.length; i++) {
		if (valExist(form.elements[i].name)) {
			var formType	= form.elements[i].type;
			var formName	= form.elements[i].name;
			var formVal		= document.getElementById(formName).value;
			//alert(formName);
			
			switch(formName) {
				//__________________________________________________ TRACKER : TTCT
				case "ttct_fd_month":
					checkFDoC	= true;
					FDoC_m		= formVal;
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the month for your First Cycle.\n";
					}
					break;
				case "ttct_fd_day":
					checkFDoC	= true;
					FDoC_d		= formVal;
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the day for your First Cycle.\n";
					}
					break;
				case "ttct_fd_year":
					checkFDoC	= true;
					FDoC_y		= formVal;
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the year for your First Cycle.\n";
					}
					break;
					
				case "ttct_lid":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the length in days.\n";
					}
					break;
					
				case "ttct_dc_month":
					checkDoCE	= true;
					DoCE_m		= formVal;
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the month for the date of your cycle event.\n";
					}
					break;
				case "ttct_dc_day":
					checkDoCE	= true;
					DoCE_d		= formVal;
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the day for the date of your cycle event.\n";
					}
					break;
				case "ttct_dc_year":
					checkDoCE	= true;
					DoCE_y		= formVal;
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose the year for the date of your cycle event.\n";
					}
					break;
					
				case "ttct_pos_month":
					if (document.getElementById("ttct_pos").checked == true) {
						checkPoS	= true;
						PoS_m		= formVal;
						if (formVal == "") {
							errNum++;
							errMsg	+= "Please choose the month for the date of your cycle event.\n";
						}
					}
					break;
				case "ttct_pos_day":
					if (document.getElementById("ttct_pos").checked == true) {
						checkPoS	= true;
						PoS_d		= formVal;
						if (formVal == "") {
							errNum++;
							errMsg	+= "Please choose the day for the date of your cycle event.\n";
						}
					}
					break;
				case "ttct_pos_year":
					if (document.getElementById("ttct_pos").checked == true) {
						checkPoS	= true;
						PoS_y		= formVal;
						if (formVal == "") {
							errNum++;
							errMsg	+= "Please choose the year for the date of your cycle event.\n";
						}
					}
					break;
					
				case "timezone":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose your timezone.\n";
					}
					break;
				
				
				//__________________________________________________ MISC
				case "_name":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please fill out your name.\n";
					}
					break;
					
				case "_email":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please fill out your email address.\n";
					} else {
						// Not blank, check against pattern
						if (!valEmail(formVal)) {
							errNum++;
							errMsg	+= "Please format your email address properly.\n";
						}
					}
					break;
					
				case "_address":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please fill out your address.\n";
					}
					break;
					
				case "_city":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please fill out your city.\n";
					}
					break;
					
				case "_state":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose your state.\n";
					}
					break;
					
				case "_country":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose your country.\n";
					}
					break;
					
				case "_howfound":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please choose how you found out about us.\n";
					}
					break;
				
				case "_captcha":
					if (formVal == "") {
						errNum++;
						errMsg	+= "Please complete the captcha.\n";
					}
					break;
			}
		}
	}
	
	// Shall we check the validity of the TTC dates?
	if (checkFDoC) { if (!isDate(FDoC_d, FDoC_m, FDoC_y)) { errNum++; errMsg += "First Day of Cycle is not a valid date.\n"; }}
	if (checkDoCE) { if (!isDate(DoCE_d, DoCE_m, DoCE_y)) { errNum++; errMsg += "Cycle Event is not a valid date.\n"; }}
	if (checkPoS) { if (!isDate(PoS_d, PoS_m, PoS_y)) { errNum++; errMsg += "POS Countdown is not a valid date.\n"; }}
	
	if (errNum >= 1) {
		alert(errMsg);
		return false;
	} else {
		return true;
	}
}

// TTCT POS Check
function posCheckCheck(checkStatus) {
	if (checkStatus) {
		document.getElementById("custom_text").value	= '';
		document.getElementById("custom_text").disabled	= true;
	
	} else {
		document.getElementById("custom_text").value	= '';
		document.getElementById("custom_text").disabled	= false;
	}
}

// Jump menu functionality
function selectJumpMenu(theUrl) {
 	if (theUrl != "") {
		  window.top.location.href = theUrl;
	 }
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

function onlyNumbers(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        //status = "This field accepts numbers only."
        return false
    }
    //status = ""
    return true
}


// Remove an icon from the icon list in the 'Your Current Icons' div
function removeIcon(iconname) {

	var removedyet = false;
	var newiconstring = '';

	// Loop through and find the one to remove
	$j("#selectedicons").attr('value').split(',').each(function(i, value) {

		if (i != '') {
			if (removedyet != true) {

				if (i != iconname) {
					newiconstring += i + ',';
				}
				else {
					removedyet = true;
				}
			}
			else {
				newiconstring += i + ',';
			}
		}
	});

	// Update the string in the selectedicons field and update the current icon display
	$j("#selectedicons").attr('value', newiconstring);

	// Update the current icon selection in the 'Your Current Icons' div at the top
	$j(".yourcurrenticons").html('');
	$j("#selectedicons").attr('value').split(',').each(function(i, value) {
			if (i != '') {
				$j(".yourcurrenticons").html( $j(".yourcurrenticons").html() + '<img src="/create/tickergraphics/' + i + '.png" /> <a href="#" onclick="javascript: removeIcon(\'' + i + '\'); return false;"><img src="/gif/del.gif" width=16 height=16 style="margin-left:2px;border:0px;" /></a><br />');
			}
		}
	);
}


/* For use in Step 2: Handle the addition to and modification of the icon choices array */
$j(document).ready(function() {

	// See if we should load the 'Your current Icons' div with something
	if ($j("#selectedicons").attr('value')) {
		$j("#selectedicons").attr('value').split(',').each(function(i, value) {
				if (i != '') {
					$j(".yourcurrenticons").html( $j(".yourcurrenticons").html() + '<img src="/create/tickergraphics/' + i + '.png" /><a href="#" onclick="javascript: removeIcon(\'' + i + '\'); return false;"><img src="/gif/del.gif" width=16 height=16 style="margin-left:2px;border:0;" /></a><br />');
				}
			}
		);
	}

	// Do something when we click on an icon
	$j(".iconcheckbox").click(function() { 

		// Determine whether or not this is one icon too many (limit is 5)
		if ($j("#selectedicons").attr('value').split(',').length > 5) {

			// Note: There'll always be a blank last entry in the  array that results from 
			// the split because of how we store icons in the list as plain text (i.e., "icon###,"). It's cool.
			alert("Er, I think 5 icons is enough.");
		}
		else {
		
			// Add the clicked-on icon to the selected icon list
			$j("#selectedicons").attr('value', $j("#selectedicons").attr('value') + this.name + ',');

			// Update the current icon selection in the 'Your Current Icons' div at the top
			$j(".yourcurrenticons").html('');
			$j("#selectedicons").attr('value').split(',').each(function(i, value) {
					if (i != '') {
						$j(".yourcurrenticons").html( $j(".yourcurrenticons").html() + '<img src="/create/tickergraphics/' + i + '.png" /><a href="#" onclick="javascript: removeIcon(\'' + i + '\'); return false;"><img src="/gif/del.gif" width=16 height=16 style="margin-left:2px;border:0;" /></a><br />');
					}
				}
			);
		}
	});
});
