/**
 * PhoneCompetitions.co.uk main.js
 * @author: Andy Thomas (email@antom.co.uk)
 * @date: 12/11/2008
 */

var ajaxRequest = null;

window.onload = function() {
	
	// Simple JS Form Validation
	checkFormFields('email_form',0);
	checkFormFields('contact_form',0);
	checkFormFields('admin_form',0);
	
	// sIFR setup
	if(typeof sIFR == "function"){
		sIFR.replaceElement(
			"body.competition-cash-and-vouchers div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#666666',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-travel div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#cc99cc',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-electrical div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#cc9999',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-motoring div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#669933',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-entertainment div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#cc9933',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-household div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#666699',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-leisure div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#663366',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-lifestyle div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#666633',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-sports div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#333366',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"body.competition-everything-else div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#990000',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"div#content h2",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#717774',
				sWmode: 'transparent'
			}));
			
		sIFR.replaceElement(
			"h3",
			named({
				sFlashSrc: '/swf/arialrounded.swf',
				sColor: '#ffffff',
				sWmode: 'transparent'
			}));
	};

	
	// external links
	externalLinks();
	
	// competitions load
	var competitions = document.getElementById('competitions');
	
	if (competitions) {
		var overlay_links = getElementsByClass('overlay_link',competitions);
		
		if (overlay_links.length > 0) {
			for(i=0;i<overlay_links.length;i++) {
			
				addEventListener(overlay_links[i],'click',function(e) {
						e = (e) ? e : window.event;
						
						var url = this.href;
						
						// load content via ajax
						doAjax(
							url,
							'ajaxformat=xhtml',
							function() {
								if (ajaxRequest) {
									switch(true) {
									
										// loading
										case (ajaxRequest.readyState == 1 || (window.opera && ajaxRequest.readyState == 2) ):
											addOverlay(
												'ol-content',
												'Test',
												400,
												200
											);
											break;
											
										// completed successfully
										case (ajaxRequest.readyState == 4 && ajaxRequest.status == 200):
											replaceOverlayLoading(
												'overlay-loaded',
												ajaxRequest.responseText
											);
											sIFR.replaceElement(
											"div#overlay-loaded h2",
											named({
												sFlashSrc: '/swf/arialrounded.swf',
												sColor: '#999999',
												sFlashVars: 'textalign=center&offsetLeft=-15',
												sWmode: 'transparent'
											}));
											break;
											
										// not found
										case (ajaxRequest.readyState == 4 && ajaxRequest.status == 404):
											alert('The page could not be found.');
											break;
											
									}
								}
							}
						);
						
						if (e.stopPropagation) {
							e.stopPropagation();
							if (e.preventDefault) {
								e.preventDefault();
							}
						} else {
							e.returnValue = false;
						}
						
						this.blur();
					},false);
					
			}
		}
	}
	
	// admin - competition delete buttons
	var edit_competitions_form = document.getElementById('edit_competitions_form');
	
	if (edit_competitions_form) {
		var delete_btn = getElementsByClass('delete_btn',edit_competitions_form);
		
		if (delete_btn.length > 0) {
			for(i=0;i<delete_btn.length;i++) {
			
				addEventListener(delete_btn[i].getElementsByTagName('a')[0],'click',function(e) {
						e = (e) ? e : window.event;
						
						if (confirm('Are you sure you want to delete this competition?')) {
							doAjax(
								this.href,
								'btnCompetitionDelete=1&ajaxformat=json&ajaxitem=delete_competition',
								function() {
									if (ajaxRequest) {
										switch(true) {
										
											// loading
											case (ajaxRequest.readyState == 1):
												break;
												
											// completed successfully
											case (ajaxRequest.readyState == 4 && ajaxRequest.status == 200):
												var deleted = eval('(' + ajaxRequest.responseText + ')');
												var tr_to_delete = document.getElementById('competition_item_' + deleted.id);
												tr_to_delete.parentNode.removeChild(tr_to_delete);
												break;
												
											// not found
											case (ajaxRequest.readyState == 4 && ajaxRequest.status == 404):
												alert('The competition could not be deleted.');
												break;
												
										}
									}
								}
							);
						}
						
						if (e.stopPropagation) {
							e.stopPropagation();
							if (e.preventDefault) {
								e.preventDefault();
							}
						} else {
							e.returnValue = false;
						}
						
						this.blur();
					},false);
					
			}
		}
	}
	
	// admin - competition featured buttons
	var edit_competitions_form = document.getElementById('edit_competitions_form');
	
	if (edit_competitions_form) {
		var featured_btn = getElementsByClass('featured_btn',edit_competitions_form);
		
		if (featured_btn.length > 0) {
			for(i=0;i<featured_btn.length;i++) {
			
				addEventListener(featured_btn[i].getElementsByTagName('a')[0],'click',function(e) {
						e = (e) ? e : window.event;
						
						doAjax(
							this.href,
							'btnCompetitionFeatured=1&ajaxformat=json&ajaxitem=featured_competition',
							function() {
								if (ajaxRequest) {
									switch(true) {
									
										// loading
										case (ajaxRequest.readyState == 1):
											break;
											
										// completed successfully
										case (ajaxRequest.readyState == 4 && ajaxRequest.status == 200):
											var featured = eval('(' + ajaxRequest.responseText + ')');
											
											var tr_to_update = document.getElementById('competition_item_' + featured.id);
											var featured_btn = getElementsByClass('featured_btn',tr_to_update);
											
											if (featured_btn.length > 0) {
												featured_btn[0].getElementsByTagName('a')[0].className = 'featured_' + featured.value;
											}
											
											break;
											
										// not found
										case (ajaxRequest.readyState == 4 && ajaxRequest.status == 404):
											alert('The featured property of competition could not be modified. Please try again.');
											break;
											
									}
								}
							}
						);
						
						if (e.stopPropagation) {
							e.stopPropagation();
							if (e.preventDefault) {
								e.preventDefault();
							}
						} else {
							e.returnValue = false;
						}
						
						this.blur();
					},false);
					
			}
		}
	}
	
	// admin - category buttons
	var edit_categories_form = document.getElementById('edit_categories_form');
	
	if (edit_categories_form) {
		var delete_btn = getElementsByClass('delete_btn',edit_categories_form);
		
		if (delete_btn.length > 0) {
			for(i=0;i<delete_btn.length;i++) {
			
				addEventListener(delete_btn[i].getElementsByTagName('a')[0],'click',function(e) {
						e = (e) ? e : window.event;
						
						if (confirm('Are you sure you want to delete this category?')) {
							doAjax(
								this.href,
								'btnCategoryDelete=1&ajaxformat=json&ajaxitem=delete_category',
								function() {
									if (ajaxRequest) {
										switch(true) {
										
											// loading
											case (ajaxRequest.readyState == 1):
												break;
												
											// completed successfully
											case (ajaxRequest.readyState == 4 && ajaxRequest.status == 200):
												var deleted = eval('(' + ajaxRequest.responseText + ')');
												var tr_to_delete = document.getElementById('category_item_' + deleted.id);
												tr_to_delete.parentNode.removeChild(tr_to_delete);
												break;
												
											// not found
											case (ajaxRequest.readyState == 4 && ajaxRequest.status == 404):
												alert('The category could not be deleted.');
												break;
												
										}
									}
								}
							);
						}
						
						if (e.stopPropagation) {
							e.stopPropagation();
							if (e.preventDefault) {
								e.preventDefault();
							}
						} else {
							e.returnValue = false;
						}
						
						this.blur();
					},false);
					
			}
		}
	}
	
	if (window.bkLib === undefined) {
		// do nothing
	} else {
		var copy_edit_content = document.getElementById('copy_edit_content');
			
		if (copy_edit_content)
			var rte = new nicEditor({fullPanel : true}).panelInstance(copy_edit_content,{hasPanel : true});
	}
}

/**
 * getElementsByClass
 * gets elements by their class name.
 */
function getElementsByClass(needle,area) {
	area = area || document;
	var my_array = area.getElementsByTagName("*");
	var retvalue = new Array();
	var j = 0;

	for (var i=0;i<my_array.length;i++) {
		var c = ' ' + my_array[i].className + ' ';
		if (c.indexOf(' ' + needle + ' ') != -1) retvalue[j++] = my_array[i];
	}
	
	return retvalue;
}

/**
 * addEventListener
 * cross browser event listener.
 */
function addEventListener(el,et,h,c) {
	if (el.addEventListener)
		el.addEventListener(et,h,c);
	else if (el.attachEvent)
		eval('el.on' + et + ' = ' + h);
}

/**
 * addOverlay
 * Add an overlay to the page.
 */
function addOverlay(id,title,width,height) {
	var o		= document.createElement('div');
	o.id		= 'overlay';
	o.className = 'overlay_' + id;
	
	// overlay background
	var ob 		= document.createElement('div');
	ob.id		= 'overlay-bg';
	o.appendChild(ob);
	
	// overlay content
	var oc				= document.createElement('div');
	oc.id				= 'overlay-content';
	oc.style.width		= width + 'px';
	oc.style.height		= (parseInt(height) + 25) + 'px';
	oc.style.marginLeft	= (width/2 * -1) + 'px';
	oc.style.marginTop	= (height/2 * -1) + 'px';
	
	// overlay loading
	var ol				= document.createElement('div')
	ol.id				= 'overlay-loading';
	ol.innerHTML		= 'Loading&hellip;';
	oc.appendChild(ol);
	
	// 'remove overlay' anchor
	var oa 		= document.createElement('a');
	oa.appendChild(document.createTextNode('Close'))
	oa.id		= 'overlay-close';
	oa.href 	= '#';
	oa.onclick 	= function(){removeOverlay();return false;}
	oc.appendChild(oa);
	
	o.appendChild(oc);
	document.body.appendChild(o);
	
	document.body.style.cursor	= 'wait';
	fadeById('overlay-bg', 0, .75, 500);
	fadeById('overlay-content', 0, 1, 500);
	setTimeout('document.body.style.cursor = "default"', 500);
}

/**
 * removeOverlay
 * Removes the overlay.
 */
function removeOverlay() {
	var o = document.getElementById('overlay');
	if (o) {
		document.body.style.cursor	= 'wait';
		fadeById('overlay-bg', .75, 0, 500);
		fadeById('overlay-content', 1, 0, 500);
		setTimeout('document.body.style.cursor = "default"', 500);
		setTimeout('document.body.removeChild(document.getElementById("overlay"))', 500);
	}
}

/**
 * replaceOverlayContent
 * replaces the overlay loading with the loaded content.
 */
function replaceOverlayLoading(id,content) {
	var ol = document.getElementById('overlay-loading');
	if (ol) {
		var oc			= document.createElement('div');
		oc.id			= id;
		oc.innerHTML	= content;
		ol.parentNode.replaceChild(oc,ol);
	}
}

function fadeById(id,from,to,duration) {
	var f = (duration > 999) ? 30 * (duration / 1000) : 30;
	var s = ((to - from) / f);
	var t = duration / f;
	
	for (i = 1; i <= f; i++) {
		setTimeout('setOpacity(document.getElementById(\'' + id + '\'),' + (from + (i*s)) + ')', i*t);
	}
}

/**
 * setOpacity
 * set the opacity for a given element;
 */
function setOpacity(el,o) {
	el.style.opacity = o;
	el.style.MozOpacity = o;
	el.style.KhtmlOpacity = o;
	el.style.filter = "alpha(opacity=" + (o * 100) + ");";
}

/**
 * externalLinks
 * open any anchor with the rel="external"
 */
function externalLinks() {
    if (!document.getElementsByTagName) return;

    var anchors = document.getElementsByTagName("a");

    for ( var i=0; i < anchors.length; i++ ) {
        var anchor = anchors[i];

        if ( anchor.getAttribute("href") && anchor.getAttribute("rel") == "external" ) {
            if ( anchor.getAttribute("className") ) {
                anchor.target = anchor.getAttribute("className");
            }
            else {
                anchor.target = "_blank";
            }
        }
    }
}

/**
 * checkFormFields
 * quick client-side validation to check that no fields on a form are left empty.
 */

function checkFormFields(byClass,usemandatory) {
	var forms = getElementsByClass(byClass,document.getElementById('content'));
	
	if (forms.length > 0) {
		for(i=0;i<forms.length;i++) {
			addEventListener(forms[i],'submit',function(e) {
				e = (e) ? e : window.event;
				
				var fields = (usemandatory) ? this.getElementsByTagName('*') : getElementsByClass('mandatory',document.getElementById('content'));
				var empty = 0;
				
				for (f=0;f<fields.length;f++) {
					if ( fields[f].value == '')
						empty++;
				}
				
				if (empty>0) {
					alert('Please fill out all fields on the form.');
					if (e.preventDefault)
						e.preventDefault();
					if (e.stopPropagation)
						e.stopPropagation();
					else
						e.returnValue = false;
				}
			},false);
		}
	}
}

/**
 * doAjax
 */
 
function doAjax(url,params,actions) {
	if (window.XMLHttpRequest)
		ajaxRequest = new XMLHttpRequest(); // IE7, Firefox, Mozilla, etc.
	else if (window.ActiveXObject)
		ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP'); // IE5 & IE6
	
	if (ajaxRequest != null) {
		ajaxRequest.open('POST', url, true);
		
		ajaxRequest.onreadystatechange = actions;
		
		ajaxRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		ajaxRequest.setRequestHeader('Content-length', params.length);
		ajaxRequest.setRequestHeader('Connection', 'close');
		
		ajaxRequest.send(params);
		
	}
	else
	{
		alert('Your browser does not support XMLHttpRequests.');
	}
	return ajaxRequest;
}