/**
* returns a boolean: true if the client browser is Internet Explorer 6 or earlier.
*/
function isIE6(){
	var MSIE = navigator.appVersion.indexOf('MSIE')
	if(MSIE<0)
		return false;
	var version = navigator.appVersion.substring(MSIE+4, navigator.appVersion.indexOf(';',MSIE+4))
	if(version<7)
		return true;
	return false;
}

/**
* returns an integer: version of Internet Explorer, 0 if not IE
*/
function ieVersion(){
	var MSIE = navigator.appVersion.indexOf('MSIE')
	if(MSIE<0)
		return 0;
	var version = navigator.appVersion.substring(MSIE+4, navigator.appVersion.indexOf(';',MSIE+4))
		return version;
}

/**
* Popin Terms and Conditions
*/
function viewTermsAndConditions(){
	var height = document.body.clientHeight - 20;
	var width = 600;
	var url = "terms_and_conditions.jsp";
	var top = 20;
	popin(url, top, height, width);
}

function popup(url) {
	window.open(url,'mg_popup','height=500,width=790,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resize=yes');
	return false;
}

/**
* Create a new iframe popin
* url: the page the iframe will contain
* top: the number of pixels from the top of the page
* width: how wide the iframe will be
* height: how high the iframe will be
*/
function popin_iframe(url, top, width, height) {
	// Create popup wrapper DIV
	var popupWrapper = document.createElement("div")
	popupWrapper.setAttribute("id","popupWrapper");
	popupWrapper.id="popupWrapper";
	popupWrapper.style.position="absolute";
	popupWrapper.style.left="0px";
	popupWrapper.style.top="0px";
        if(navigator.appVersion.indexOf('MSIE')<0)
            popupWrapper.style.height=outerHeight+"px";
        else
            popupWrapper.style.height=document.body.scrollHeight+"px";
	popupWrapper.style.width="100%";
	if(isIE6())	popupWrapper.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/mask.png',sizingMethod='scale')";
	else	popupWrapper.style.backgroundImage="url(/images/mask.png)";
	popupWrapper.style.zIndex="10";

	// Create popup DIV
	var popup = document.createElement("div");
	popup.setAttribute("id","popup");
	var left = (document.body.clientWidth - width)/2 + document.body.offsetLeft - 2;
	popup.style.position="absolute";
	popup.style.top=top+"px";
	popup.style.left=left+"px";

	// Create close button
	var closeButton = '';
        /*'<span style="background-image:url(images/button.png);background-repeat:no-repeat;height:20px;width:92px;display:block;padding-top:11px;text-align:center;color:#CC0000;font-weight:bold;position:relative;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/button.png\',sizingMethod=\'scale\');" onclick="document.getElementById(\'popupWrapper\').parentNode.removeChild(document.getElementById(\'popupWrapper\'))">CLOSE</span>'
	if(isIE6()) closeButton = '<span style="height:20px;width:92px;display:block;padding-top:11px;text-align:center;color:#CC0000;font-weight:bold;position:relative;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/button.png\',sizingMethod=\'scale\');" onclick="document.getElementById(\'popupWrapper\').parentNode.removeChild(document.getElementById(\'popupWrapper\'))">CLOSE</span>';*/

	// Attach iframe
	var iframe = '<iframe width="'+width+'" height="'+height+'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+url+'"></iframe>'
	popup.innerHTML = closeButton+'<div style="border: 2px solid #FFFFFF; background-color:#999999; background-image:url(images/magbutton.gif);background-repeat:no-repeat; background-position:center center;">'+iframe+'</div>';
	popupWrapper.appendChild(popup);
	document.body.appendChild(popupWrapper);
}

/**
* Created by Tom Curran
* An JavaScript Ajax object
* Usage:
*   var myAjax = new MG_Ajax();
*   myAjax.url = "/the.Relative.Url";
*   myAjax.handleResponse = function() {
*       alert("Handle your "+myAjax.request.responseTest+" here.");
*   }
*/
var MG_Ajax = function(){
	this.url	= "";
	this.handleResponse = function() {
			if (this.request.readyState==4) {
				alert("This AJAX script has no event handler.");
			}
	}

	this.method = "GET";
	this.async	= true;
	this.request = null;
	this.init = function(){
			try	{
				// Firefox, Opera 8.0+, Safari
				this.request = new XMLHttpRequest();
			} catch (e) {
				// Internet Explorer
				try {
					this.request = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					this.request = new ActiveXObject("Microsoft.XMLHTTP");
				}
			}
			if(this.request) {
				var self = this;
				this.request.onreadystatechange = function() {
					if (self.request.readyState==4) {
						if(self.request.status>=300 && self.request.status<400) {
							alert("Your session has ended.\nAny unsaved data has been lost.");
							window.parent.location = window.parent.location;
						} else {
							self.handleResponse();
						}
					}
				}
                                 try{
        				this.request.open(this.method, this.url, this.async);
        				this.request.send(null);
					if (!this.async && this.request.onreadystatechange==null && self.request.readyState==4) { // hack for FF synchronous calls
						self.handleResponse();
					}
				} catch(err){
                                    alert("Permission denied for AJAX lookup of "+this.url);
                             }
			}
	}
}

/**
* Create a new ajax popin
* url: the page the ajax will contain
* top: the number of pixels from the top of the page
* width: how wide the div will be
* height: how high the div will be
*/
function popin_ajax(url, top, width, height, useAsync) {
	// Create popup wrapper DIV
	var popupWrapper = document.createElement("div")
	popupWrapper.setAttribute("id","popupWrapper");
	popupWrapper.id="popupWrapper";
	popupWrapper.style.position="absolute";
	popupWrapper.style.left="0px";
	popupWrapper.style.top="0px";
//        if(navigator.appVersion.indexOf('MSIE')<0)
//            popupWrapper.style.height=(outerHeight + 400)+"px";
//        else
        popupWrapper.style.height=(document.getElementById("wrapper").scrollHeight + 400) +"px";
	popupWrapper.style.width="100%";
	//if(isIE6())	popupWrapper.style.filter="alpha(opacity=70)";
	var ourIeVersion = ieVersion();
	if (ourIeVersion == 6.0 || ourIeVersion == 7.0) 
	{
		popupWrapper.style.filter="alpha(opacity=70)";
	} else	
	{
		popupWrapper.style.opacity="0.7";
	}
	popupWrapper.style.backgroundColor="#000000";
	popupWrapper.style.zIndex="1";

        // Create popup DIV
        var popup = document.createElement("div");
        popup.setAttribute("id","popup");
        popup.id="popup";
        var left = (document.body.clientWidth - width)/2 + document.body.offsetLeft - 2;
        popup.style.position="absolute";
        popup.style.top=top+"px";
        popup.style.left=left+"px";
	popup.style.zIndex="2";

        // Create close button
        //var closeButton = '<span style="background-image:url(images/button.png);background-repeat:no-repeat;height:20px;width:92px;display:block;padding-top:11px;text-align:center;color:#CC0000;font-weight:bold;position:relative;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/button.png\',sizingMethod=\'scale\');" onclick="document.getElementById(\'popupWrapper\').parentNode.removeChild(document.getElementById(\'popupWrapper\'))">CLOSE</span>'
        //if(isIE6()) closeButton = '<span style="height:20px;width:92px;display:block;padding-top:11px;text-align:center;color:#CC0000;font-weight:bold;position:relative;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/button.png\',sizingMethod=\'scale\');" onclick="document.getElementById(\'popupWrapper\').parentNode.removeChild(document.getElementById(\'popupWrapper\'))">CLOSE</span>';

        // Get Ajax
        var ajax = new MG_Ajax();
        ajax.url = url;
        if(typeof useAsync != 'undefined') ajax.async = useAsync;
        ajax.popup = popup;
        ajax.popupWrapper = popupWrapper;
//        ajax.closeButton = closeButton;
        ajax.handleResponse = function() {
            ajax.popup.innerHTML = ajax.request.responseText;
//            ajax.popupWrapper.appendChild(ajax.popup);
            document.body.appendChild(ajax.popupWrapper);
            document.body.appendChild(ajax.popup);
	}
	ajax.init()
}

function close_popin() {
    document.body.removeChild(document.getElementById('popup'))
    document.body.removeChild(document.getElementById('popupWrapper'))
}
/**
* Appends an ajax div to an existing div
* url: the page the ajax will contain
* wrapperDiv: the div object that will contain the new element
* id: the id to give the new ajax element
*/
function insertAjax(url, wrapperDiv, id, useAsync){
    var newDiv = document.createElement("div");
    newDiv.setAttribute("id",id);
    newDiv.id = id;
    
    // Get Ajax
    var ajax = new MG_Ajax();
    ajax.url = url;
    if(typeof useAsync != 'undefined') ajax.async = useAsync;
    ajax.newDiv = newDiv;
    ajax.wrapper = wrapperDiv;
    ajax.handleResponse = function() {
        ajax.newDiv.innerHTML = ajax.request.responseText;
        ajax.wrapper.appendChild(ajax.newDiv);
    }
    ajax.init()
}

/**
* Replaces the contents of a div with an ajax element
* url: the page the ajax will contain
* wrapperDiv: the div object that will contain the new element
*/
function replaceAjax(url, wrapperDiv, useAsync){
    var ajax = new MG_Ajax();
    ajax.url = url;
    if(typeof useAsync != 'undefined') ajax.async = useAsync;
    ajax.wrapper = wrapperDiv;
    ajax.handleResponse = function() {
        var newDiv = document.createElement("div");
        newDiv.innerHTML = ajax.request.responseText;
        ajax.wrapper.innerHTML = "";
        ajax.wrapper.appendChild(newDiv);
        if(navigator.appVersion.indexOf('MSIE')>=0) {
            execScript(ajax.request.responseText);
        }
    }
    ajax.init()
}

function execScript(text){
    var start = text.indexOf("<script");
    if(start>=0) start=text.indexOf(">",start)+1;
    var end = text.indexOf("</script",start);
    while(start>=0&&end>=start){
        var js = text.substring(start,end);
        eval(js);
        start = text.indexOf("<script", end);
        if(start>=0) start=text.indexOf(">",start)+1;
        end = text.indexOf("</script",start);
    }
}

/*
*   value: The value you wish to have selected or __SELECT_ALL__ to have all selected
*   post: An array of options to be appended to the end of the select
*/
function addOptions(url, select, value, post){
	var ajax = new MG_Ajax();
	ajax.url = url;
	ajax.select = select;
	ajax.value	= value;
	ajax.post	= post;
	ajax.handleResponse = function() {
		var xml = ajax.request.responseXML.documentElement;
		var elements = xml.getElementsByTagName("option");
		for(var i=0; i<elements.length; i++) {
			var option = document.createElement("option")
			option.value	= elements[i].getAttribute('value');
			option.text		= elements[i].firstChild.nodeValue;
			option.selected= elements[i].getAttribute('selected');
			option.disabled= elements[i].getAttribute('disabled');
			if(elements[i].getAttribute('style')!=null && elements[i].getAttribute('style').indexOf('font-style:')>=0) {
				var start = elements[i].getAttribute('style').indexOf('font-style:')+11
				var end = elements[i].getAttribute('style').indexOf(";",start);
				if(end < start) end = elements[i].getAttribute('style').length;
				option.style.fontStyle = elements[i].getAttribute('style').substring(start,end)
			}

			if((ajax.value=="__SELECT_ALL__") || (ajax.value==option.text)) 
				option.selected = true;

			ajax.select.add(option,null);
		}
		if(ajax.post!=null){
			for(var i=0; i<ajax.post.length; i++) {
				if((ajax.value=="__SELECT_ALL__") || (ajax.value==ajax.post[i].text)) 
					post[i].selected = true;
				ajax.select.add(ajax.post[i],null);
			}
		}
	}
	ajax.init()
}

/**
* Tabs
*/
var allTabs = [[]];
function initTabs(){
    if(typeof allTabs == 'undefined')
        allTabs = [[]];
    for(var a=0; a<allTabs.length; a++){
        var tabs = allTabs[a];
        if(typeof tabs != 'undefined'){
            for(var b=0; b<tabs.length; b++) {
                var id = tabs[b];
                document.getElementById(id+"_tab").divId = id;
                document.getElementById(id+"_tab").tabsId = a;
                document.getElementById(id+"_tab").onclick = function(){showTab(this.divId,this.tabsId);};
            }
            if(tabs.length!=0)
                showTab(tabs[0],a);
        }
    }
}
function showTab(id, tabsId) {
    var tabs = allTabs[tabsId];
    for(var a=0; a<tabs.length; a++){
        var tab = tabs[a];
        document.getElementById(tab+"_tab").className = "";
        document.getElementById(tab).style.display = "none";
    }
    document.getElementById(id+"_tab").className = "selected";
    document.getElementById(id).style.display = "";
}

/**
* onload
*/
var allOnLoad = new Array();
function addOnLoad(newFunction){
    if(window.onload){
        if(window.onload != runOnLoad){
            allOnLoad.push(window.onload);
            window.onload=runOnLoad;
        }
    } else {
        window.onload = runOnLoad;
    }
    allOnLoad.push(newFunction);
}
function runOnLoad(){
    for(var i=0; i<allOnLoad; i++){
        if(typeof allOnLoad[i]=="function"){
            allOnLoad[i]();
        }
    }
}

function toggleVisibility(id) {
      var d = document.getElementById(id);
      if (d.style.display == "none" || (d.className.indexOf("hide") >= 0 && d.style.display  == "") ) {
              showElement(id);
      } else {
              hideElement(id);
      }
      return false;
}
var prevToggleObj;
function toggleStyle(obj, style_1, style_2, flipPrevious) {
	if(typeof flipPrevious != 'undefined') flipPrevious = new Boolean(flipPrevious);
	else flipPrevious = false;
	if (obj.className.indexOf(style_1) >= 0) {
	        obj.className = style_2;
	} else {
	        obj.className = style_1;
	}
	if(flipPrevious) {
		if (prevToggleObj != null) {
			toggleStyle(prevToggleObj, style_1, style_2);
		}
		prevToggleObj = obj;
	}
	return false;
}

function showElement(id) {
      var d = document.getElementById(id);
      d.style.display = "block";
}

function hideElement(id) {
      var d = document.getElementById(id);
      d.style.display = "none";
}

function resetInputIfDefault(obj, copy) {
    if (obj.value == copy) { 
	obj.value='';
	obj.style.fontStyle='';
	obj.style.color='';
    } else if (obj.value == '') { 
	obj.value=copy;
	obj.style.fontStyle='italic';
	obj.style.color='#CCCCCC';
    }
    return false;
}

function mg_form_validate(formId, inlineErrorBool, doSubmit) {
	/*
	expects to have matching css classes for each of the rules.
	*/
	var showInlineError = true;
	var doSubmitForm = true;
	var elemToFocus = "";
	if(typeof inlineErrorBool != 'undefined') showInlineError = new Boolean(inlineErrorBool);
	if(typeof doSubmit != 'undefined') doSubmitForm = new Boolean(doSubmit);
	rules = {
		"validate_number"	: new RegExp("^[\\d]*$","ig"),
		"validate_alpha"	: new RegExp("^[\\w\\s\'-]*$","ig"),
		"validate_alphanum"	: new RegExp("^[\\w\\d\\s\\t\\n£$-+_\\.,;:\'\"]*$","ig"),
		"validate_decimal"	: new RegExp("^[\\d]*\\.?[\\d]*$","ig"),
		"validate_notnull"	: new RegExp(".+","ig"),
		"validate_telephone" : new RegExp("(?!.*([0-9])\\1{4,11})(?!.*(12345|23456|34567|45678|56789|67890|09876|98765|87654|76543|65432|54321))(^(01)[0-9]{8,9}|^(?=^(0207|0208|0203|023|024|028|029|070|074|075|07624|077|078|079|030|033|034|037|055|056))[0-9]{11})$"),
		"validate_email"	: new RegExp("^([0-9a-zA-Z]+[-\\._+&])*[0-9a-zA-Z-\\._+&]+@([-0-9a-zA-Z]{2,}[\\.])+[a-zA-Z]{2,6}$","ig"),
		"validate_postcode"	: new RegExp("^[ ]*(BFPO[ c\\/o]?[ ]?[0-9]{1,4}|GIR[ ]?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]*[0-9][ABD-HJLNP-UW-Z]{2})[ ]*$","ig"),
		"validate_name_length"	: new RegExp(".{2,}","ig")
	};
	var f = document.getElementById(formId);
	var showFinalAlert = false;
    try{
	for (y in f.elements){
		if (f.elements[y] && f.elements[y].type != null && (f.elements[y].type == "text" || f.elements[y].type == "textarea" || f.elements[y].type == "password" || f.elements[y].type == "checkbox" || f.elements[y].type.indexOf("select") >= 0 ) ) {
			for (x in rules) {
				if (f.elements[y].className.search(RegExp("\\bvalidate_telephone\\b")) >=0){
					f.elements[y].value = f.elements[y].value.replace(/[\s-\(\)]/g,"").replace(/\+44[0]{0,1}/,"0");
				}
				if (f.elements[y].className.search(RegExp("\\bvalidate_email\\b")) >=0){
					var msg=document.getElementById("emailV");
					if(msg!=null&&msg.innerHTML.indexOf("EMAIL INVALID")>=0){
						f.elements[y].className += " validate_fieldError";
						if (showInlineError == true) {
							alert("Please check " + f.elements[y].name.replace("_"," ") +" = " + f.elements[y].value);
							f.elements[y].focus();
							return false;
						} else {
							showFinalAlert = true;
							elemToFocus = f.elements[y];
							break;
						}
						
					}
					else{
						 f.elements[y].value = f.elements[y].value.replace(" ","");
					}
					 
					
					 
				}				
				if (typeof f.elements[y].className != 'undefined' && f.elements[y].className.indexOf("validate_fieldError") > 0) {
					f.elements[y].className = f.elements[y].className.replace("validate_fieldError","");
					if (f.elements[y].type == 'checkbox') {
						f.elements[y].parentNode.className = f.elements[y].parentNode.className.replace("validate_fieldError","");
					}
				}
				if ( (f.elements[y].type == 'text' || f.elements[y].type == "textarea" || f.elements[y].type == 'password') && typeof f.elements[y].className != 'undefined' && f.elements[y].className.search(RegExp("\\b"+x+"\\b")) >=0 && f.elements[y].value.search(rules[x]) < 0) {
					f.elements[y].className += " validate_fieldError";
					if (showInlineError == true) {
						alert("Please check " + f.elements[y].name.replace("_"," ") +" = " + f.elements[y].value);
						f.elements[y].focus();
						return false;
					} else {
						showFinalAlert = true;
						elemToFocus = f.elements[y];
						break;
					}
				} else if ( f.elements[y].type == 'checkbox' && f.elements[y].checked != true && typeof f.elements[y].className != 'undefined' && f.elements[y].className.search(RegExp("\\b"+x+"\\b")) >=0  ) {
					f.elements[y].className += " validate_fieldError";
					f.elements[y].parentNode.className += " validate_fieldError";
					if (showInlineError == true) {
						alert("Please check " + f.elements[y].name.replace("_"," ") +" = " + f.elements[y].value);
						f.elements[y].focus();
						return false;
					} else {
						showFinalAlert = true;
						elemToFocus = f.elements[y];
						break;
					}
				} else if ( f.elements[y].type.indexOf('select') >=0 && (f.elements[y].selectedIndex < 0 || f.elements[y].options[f.elements[y].selectedIndex].value == "") && typeof f.elements[y].className != 'undefined' && f.elements[y].className.search(RegExp("\\b"+x+"\\b")) >=0 ) {
					f.elements[y].className += " validate_fieldError";
					if (showInlineError == true) {
						alert("Please check " + f.elements[y].name.replace("_"," ") +" = " + f.elements[y].value);
						f.elements[y].focus();
						return false;
					} else {
						showFinalAlert = true;
						elemToFocus = f.elements[y];
						break;
					}
				}
			}
    	}
	}
	} catch(err) {
		//console.log(err.toString());
	}
	if (showFinalAlert == true){
		alert("Please check you responded to all the fields correctly.");
		try {
			window.scrollTo(0,findPos(elemToFocus)[1]-40);
		} catch (err) {
		}
		return false;
	} else if (doSubmitForm == true){
		f.submit();
		return false;
	}
	else{
		return true;
	}
}


/*####  Lee's JS additions #### */

function getObj(id)
{
	return document.getElementById(id);
}

function checkAccountLink(pageName)
{
	var curHref = pageName.split(".jsp")[0];	
	var linkObj = getObj(curHref+"_link");
	if (linkObj != null)
	{
		linkObj.className = 'highlight_colour';
	}
}


function addCategoryEvent()
{
	var className = "category_item";
	var className2 = "prize_list_item";	
	var elements=document.getElementsByTagName("div");
	for(var i=0;i<elements.length;i++)
	{
		if (elements[i].getAttribute("class")==className||elements[i].className==className || elements[i].getAttribute("class")==className2||elements[i].className==className2)
		{
			elements[i].onmouseover=function(){
				moveCategoryTransImage(this);
				return false;
			}
			elements[i].onmouseout=function(){
				removeCategoryTransImage(this);
				return false;
			}			
		}
	}
}

function moveCategoryTransImage(obj)
{
	obj.style.backgroundImage="url(images/Default/selectedlink_white137.png)";
}
function removeCategoryTransImage(obj)
{
	obj.style.backgroundImage="";
}

function findPos(obj)
{
	var curleft=curtop=0;
	if(obj.offsetParent)
	{
		curleft=obj.offsetLeft;
		curtop=obj.offsetTop;
		while(obj==obj.offsetParent)
		{
			curleft+=obj.offsetLeft;
			curtop+=obj.offsetTop;
		}
	}
	return[curleft,curtop];
}

function applyDOMAlterations()
{
	var hrefParts = window.location.href.split("/");
	var pageName = hrefParts[hrefParts.length-1];

	if (pageName.indexOf("my_account") != -1)
	{
		checkAccountLink(pageName);
	}
	
	if (pageName.indexOf("index.jsp") != -1)
	{
		addCategoryEvent();
	}
	
	if (window.location.href.indexOf("/enter/") != -1 || window.location.href.indexOf("competition") != -1 || window.location.href.indexOf("microsite") != -1 || window.location.href.indexOf("ad_preview") != -1)
	{
		//temporary client hack
		if (document.getElementById('1788_192') != null) {
			document.getElementById('1788_192').value = "fashion";
		}
		if (document.getElementById('843_877') != null) {
			document.getElementById('843_877').value = "travellers club";
		}
		if (document.getElementById('642_23') != null) {
			MG_AD_RULES['642'].questions['642_23'].passwdVerify = document.getElementById('642_11');
		}
		if (document.getElementById("question_wrapper_579_676") != null && document.getElementById("question_wrapper_579_676").getElementsByTagName("select").length > 0) {
            document.getElementById("question_wrapper_579_676").getElementsByTagName("select")[0].size=6
        }
        if (document.getElementById("question_wrapper_580_676") != null && document.getElementById("question_wrapper_580_676").getElementsByTagName("select").length > 0) {
            document.getElementById("question_wrapper_580_676").getElementsByTagName("select")[0].size=6
        }
	}
	
}

window.onload=applyDOMAlterations;
