var sBrowserVersion = navigator.appVersion;

var IE = (document.all) ? true : false;
var IE4 = (IE && !document.getElementById) ? true : false;
var IE5 = (IE && document.getElementById) ? true : false;
var IE6 = IE5 ? (sBrowserVersion.match(/MSIE 5/) ? false : true) : false;

var NS4 = (document.layers) ? true : false;
var NS6 = (document.getElementById && !IE) ? true : false;

var map;
var geocoder;
var gsZoom;

//-----------------------------------------------------------------------------------------
// Google mapping
//-----------------------------------------------------------------------------------------

function loadMap( lsPostcode, lsZoom) {
    if (GBrowserIsCompatible() && document.getElementById("map")) {
        var bounds = new GLatLngBounds();
        map = new GMap2(document.getElementById("map"));
        geocoder = new GClientGeocoder();
        //map.addControl(new GSmallZoomControl());
        map.addControl(new GSmallMapControl());
        //map.addControl(new GMapTypeControl());
        
        map.setCenter( new GLatLng(0,0), 7);
        geocoder.getLocations( lsPostcode, addAddressToMap);
        gsZoom = lsZoom;
    }
    else 
    {
        //alert("Sorry, mapping feature not compatible with this browser");
    }
}

function addAddressToMap(response) 
{
  map.clearOverlays();
  if (!response || response.Status.code != 200) 
  {
    //alert("Sorry, we were unable to geocode that address");
  } 
  else 
  {
    place = response.Placemark[0];
    bounds = new GLatLngBounds();
    point = new GLatLng( place.Point.coordinates[1], place.Point.coordinates[0]);
    bounds.extend( point);
    map.setZoom( map.getBoundsZoomLevel(bounds));
    map.setCenter( bounds.getCenter(), gsZoom);
    marker = new GMarker(point);
    map.addOverlay(marker);
    //map.openInfoWindowHtml(map.getCenter(), '<b style="font-family:arial">Lincoln City Football</b>');
  }
}


//-----------------------------------------------------------------------------------------

function ValidateLogin( loInputForm)
{
	var sErrors =''
	var bErrors, loForm;
	try
	{
		gbFieldFocus = false;
		loForm = GetForm(loInputForm);
			
		sErrors += RequiredField(loForm, "Password", "Password")
				+ ValidField(loForm, "email", "Email", "Email address")
		bErrors = Boolean(sErrors);
		
		if (bErrors)
		{
			sErrors = "Please complete the following in your form:\n\n"
				+ sErrors;
			alert(sErrors);
		}
		else
		{
			document.body.style.cursor='wait';
		}
	}
	catch (eError)
	{
		alert('eError: ' + eError.description);
		bErrors = true;
	}
	return (!bErrors);
}

//-----------------------------------------------------------------------------------------

function IsIn(inArray, inItem)
{
	var iArrayIndex, bIsIn;
	bIsIn = false;
	for (iArrayIndex in inArray)
	{
		if (inArray[iArrayIndex] == inItem)
		{
			bIsIn = true;
			break;
		}
	}
	return(bIsIn);
}

//---------------------------------------------------------------------------

function ScrollToEnd()
{
	window.scrollTo(0,999999);
}

//---------------------------------------------------------------------------

/* use this to find width (& height) : javascript:alert(document.body.clientWidth) */

var winPopup;

function popupWindow(strUrl, intWidth, intHeight, strName, bNoScroll, bWindowFeatures, bPopunder)
{
	var sParams, iScreenX, iScreenY;
	if (!strName)
	{
		strName = 'winPopup';
	}

	if(window.screen)
	{
		intWidth = (intWidth ? Math.min(intWidth, window.screen.availWidth-45) : window.screen.availWidth-45);
		intHeight = (intHeight ? Math.min(intHeight, window.screen.availHeight-60) : window.screen.availHeight-60);

		iScreenX = (window.screen.availWidth - intWidth) /2
		iScreenY = (window.screen.availHeight - 20 - intHeight) /2
	}

	//alert(iScreenX + '::' + intWidth)
	//alert(iScreenY + '::' + intHeight)

	sParams = (bWindowFeatures ? 'toolbar=1,titlebar=1,status=1,' : 'toolbar=0,titlebar=0,status=0,') 
		+ 'scrollbars=' + (bNoScroll ? 0 : 1) + ',resizable=' + (bNoScroll ? 0 : 1) 
		+ (intWidth ? ',width=' + intWidth : '') + (intHeight ? ',height=' + intHeight : '')
		+ ",left=" + iScreenX + ",top=" + iScreenY + ",screenX=" + iScreenX + ",screenY=" + iScreenY ;
		
	winPopup = window.open(strUrl, strName, sParams);
	if (bPopunder && winPopup)
	{
		window.focus()
	}
	else if (winPopup)
	{
		winPopup.focus();
	}
	return (winPopup);
}

function popupNoScrollWindow(strUrl, intWidth, intHeight, strName, bPopunder)
{
	winPopup = popupWindow(strUrl, intWidth, intHeight, strName, true, false, bPopunder)
	return (winPopup);
}

function popupNormal(strUrl, strName)
{
	if (!strName)
	{
		strName = 'winPopup';
	}
	winPopup = window.open(strUrl, 'winPopup');
	return (winPopup);
}

//-----------------------------------------------------------------------------------------


function SelectAllCheckboxes(sCheckBoxName, bSelValue)
{
	var oCheckBoxes, j
	oCheckBoxes = document.getElementsByName(sCheckBoxName);
	for(j = 0; j < oCheckBoxes.length; j++) 
	{
		oCheckBoxes[j].checked = bSelValue
	}
}

//-----------------------------------------------------------------------------------------


function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

//-----------------------------------------------------------------------------------------

function InStr(strSearch, charSearchFor)
{
            for (i=0; i < strSearch.length; i++)
            {
                  if (charSearchFor == Mid(strSearch, i, 1))
                  {
                        return i;
                  }
            }
            return -1;
}

//-----------------------------------------------------------------------------------------

function isValidPostcode(p) {
	var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2}[A-Z]? ?[0-9][A-Z]{2}/i;
	return postcodeRegEx.test(p);
}

//-----------------------------------------------------------------------------------------

function hideShow(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

//-----------------------------------------------------------------------------------------

function disableForm(theform) 
    {
    if (document.all || document.getElementById) {
        for (i = 0; i < theform.length; i++) {
        var tempobj = theform.elements[i];
        if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
        tempobj.disabled = true;
        }
        setTimeout('alert("Your form has been submitted.  Notice how the submit and reset buttons were disabled upon submission.")', 2000);
        return true;
        }
        else {
        alert("The form has been submitted.  But, since you're not using IE 4+ or NS 6, the submit button was not disabled on form submission.");
        return false;
       }
    }
    
//-----------------------------------------------------------------------------------------

function addOption(selectbox,text,value )
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
    selectbox.selectedIndex = selectbox.options.length-1;
}

//-----------------------------------------------------------------------------------------


function GetXmlHttpObject() {
    var xmlHttp=null;
    try{
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e) { 
        try {
            // Internet Explorer
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

//-----------------------------------------------------------------------------------------

var gsServiceURL, gsServiceLayer, gsServiceList, 
    gsFormIDList, gsFormValueList, goFormSearch, gbAddItem;
    
function populateFromService(lsFunction) {
    
    eval(lsFunction);
    
    var aSuggestions = Array();
    var sTextboxValue = goFormSearch.value;
    var liID, liValue, laTempArray;
    
    
    bTypeAhead=false;
    if (sTextboxValue.length > 0){
        xmlHttp=GetXmlHttpObject();
        if (xmlHttp==null) {
            alert ("Your browser does not support AJAX!");
            return;
        } 
        var url = gsServiceURL + sTextboxValue + "&sid=" + Math.random();
        xmlHttp.onreadystatechange = stateChanged;
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }
    else {
        document.getElementById(gsServiceLayer).innerHTML = '';
        document.getElementById(gsServiceLayer).style.display = 'none';
    }
    function stateChanged() { 
        var lsResponseStr;
        if (xmlHttp.readyState==4){
            document.getElementById(gsServiceLayer).innerHTML = '';
            document.getElementById(gsServiceLayer).style.display = 'block';
            lsResponseStr = xmlHttp.responseText;
            
            if (lsResponseStr.length>0) {
                laArrayList = lsResponseStr.split("^");
                for (var i=0; i < laArrayList.length; i++) {
                    if (laArrayList[i].length > 0) {
                        laTempArray = laArrayList[i].split("|");
                        liValue = laTempArray[0];
                        liID = laTempArray[1];
                        document.getElementById(gsServiceLayer).innerHTML += '<input type="checkbox" ' + checkIfExists(liID) + ' onClick="processServiceList(\''+lsFunction+'\',\''+liID+'\',this.value,this.checked)" value="' + liValue + '" id="check'+i+'"> <label for="check'+i+'">' + liValue + '</label><br />';
                    }
                }
            }
            else if (gbAddItem && sTextboxValue.length>=3) {
                document.getElementById(gsServiceLayer).innerHTML += sTextboxValue + ' <a href="#" onClick="goFormSearch.value=\'\';processServiceList(\''+lsFunction+'\',\'-1\',\'' + sTextboxValue + '\',true);return false;" >Add New Product</a>';
            }
            else {
                document.getElementById(gsServiceLayer).style.display = 'none';
            }
        }
    } 
} //populateFromservice

function processServiceList( lsFunction, liID, liValue, lbAddElement) {
    eval(lsFunction);
    
    var laIDArray = gsFormIDList.value.split(",");
    var laeventvaluelistArray = gsFormValueList.value.split("^");
    
    
    gsFormIDList.value = ',';
    gsFormValueList.value = '^';
    document.getElementById(gsServiceList).innerHTML = '';
    
    
    for (var i=0; i < laIDArray.length; i++) { 
        if ((laIDArray[i] != liID || (laIDArray[i]==-1 && laeventvaluelistArray[i]!=liValue)) && laIDArray[i]!=''){
            gsFormIDList.value += laIDArray[i] + ',';
            gsFormValueList.value += laeventvaluelistArray[i] + '^';
            document.getElementById(gsServiceList).innerHTML += laeventvaluelistArray[i] + ' <a href="#" onClick="processServiceList(\''+lsFunction+'\',\'' + laIDArray[i] + '\',\'' + laeventvaluelistArray[i] + '\',false); return false;">remove</a><br />';
        }
    }
    
    if (lbAddElement) {
        gsFormIDList.value += liID + ',';
        gsFormValueList.value += liValue + '^';
        document.getElementById(gsServiceList).innerHTML += liValue + ' <a href="#" onClick="processServiceList(\''+lsFunction+'\',\'' + liID + '\',\'' + liValue + '\',false); return false;">remove</a><br />';
    }
    populateFromService( lsFunction)
    if (gsFormIDList.value!=',')
        document.getElementById(gsServiceList).style.display = 'block';
    else
        document.getElementById(gsServiceList).style.display = 'none';
} //processServiceList

//-----------------------------------------------------------------------------------------

function checkIfExists( liID) {
    if (liID!=-1) {
        var laIDArray = gsFormIDList.value.split(",");
        for (var i=0; i < laIDArray.length; i++) { 
            if (laIDArray[i] == liID)
                return 'checked';
        }
    }
}

//-----------------------------------------------------------------------------------------

function validEmail(sEmail, bOptional, lbReturnBool)
{
	var bEmail, sValidChar, sEmailPattern, oEmailRe, sError;
	bEmail = false;
	sError = "";
	if (sEmail && sEmail.length > 0)
	{
		sValidChar = "[\\w\\-\\_\\.']+";
		sEmailPattern = "^\\s*" + sValidChar + 
			"@(" + sValidChar + "\\.)+" + sValidChar + "\\s*$"
		oEmailRe = new RegExp(sEmailPattern);
		if (sEmail.match(oEmailRe))
		{
			bEmail = true;
		}
		else
		{
			sError = "invalid email format (should be username@domain.com)\n";
		}
	}
	else if (!bOptional)
	{
		sError = "required\n";
	}
	return(bEmail);
}

//-----------------------------------------------------------------------------------------

function validPostcode(sPostcode)
{
	var bValid, sPostcodePattern, oPostcodeRe, sLetter, sAlphaNumeric, sDigit;
	bValid = false;
	if (sPostcode && sPostcode.length >= 5 && sPostcode.length <= 9)
	{
		sLetter = "[A-Za-z]"
		sAlphaNumeric = "[A-Za-z0-9]"
		sDigit = "[0-9]"
		sPostcodePattern = '^\\s*' + sLetter + sAlphaNumeric + '{1,3}\\s*' + sDigit + sAlphaNumeric + '{2}\\s*$'
		oPostcodeRe = new RegExp(sPostcodePattern)
		if (sPostcode.match(oPostcodeRe))
		{
			bValid = true;
		}
	}
	return bValid;
}

//-----------------------------------------------------------------------------

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

//-----------------------------------------------------------------------------

function urlClick( loLink, liBannerID) 
{
    loLink.href = gsBaseURL + '/?bid='+ liBannerID + '&url=' + URLEncode(loLink.href);
    return false;
}

//-----------------------------------------------------------------------------