var lightbox = null;


// ------------------------------------------------------------------------------------
// EVERYTHING FROM HERE RUNS EACH TIME THE SCRIPT IS LOADED
// ------------------------------------------------------------------------------------

this.imagePreview = function(){
	/* CONFIG */

		xOffset = 5;
		yOffset = 10;

		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result

	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.id +"' alt='Image preview' />"+ c +"</p>");
		$("#preview")
			.css("top",(e.pageY - 100 - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#preview").remove();
    });
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - 100 - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};



function validateBrowse()
{
  if (document.getElementById("info").value == "")
  {
    browseEmpty();
    return(false);
  }
  else
  return(true);
}
function browseEmpty()
{
     Modalbox.show('<div class=\'warning\'><p>Oops, you didn\'t tell me what to find.<br><br>Click on any of the words to select them, and again to de-select them.  Clicking on section title will clear that entire section.</p> <input type=\'button\' value=\'Try again\' onclick=\'Modalbox.hide();\' /></div>',{title: "Empty Search", width: 300});
}

function validateSearch()
{
  var terms=document.forms[0].elements;
  var tmp="";
  for (var i=0; i < terms.length; i++)
  {
    //alert(terms[i].name + " " + terms[i].name.substr(0,1));
    if (terms[i].name.substr(0,1) == "_")
    {
    tmp = tmp + getFieldValue(terms[i]);
    }
  }
  //alert(terms.length + "/" + tmp);
  if (tmp.length == 0)
  {
    searchEmpty();
    return(false);
  }
  else
    return(true);

}
function searchEmpty()
{
     Modalbox.show('<div class=\'warning\'><p>Oops, you didn\'t tell me what to find.<BR><BR>Select from one or more drop-down lists, select some check boxes (for style, subject or concept) or enter words into the search fields then click on <I>Find</I>.</p> <input type=\'button\' value=\'Try again\' onclick=\'Modalbox.hide();\' /></div>',{title: "Empty Search", width: 300});
}

function confirmDelete()
{
  var o=document.getElementById('delete');
  if (o.checked)
  {
     Modalbox.show('<div class=\'warning\'><p>Are you sure to delete this image?</p> <input type=\'button\' value=\'Yes, delete!\' onclick=\'document.getElementById(\"button\").value=\"Delete Image\";Modalbox.hide()\' /> or <input type=\'button\' value=\'No, leave it!\' onclick=\'Modalbox.hide();document.getElementById(\"delete\").checked=false;document.getElementById(\"button\").value=\"Update image information\";\' /></div>',{title: "Delete this image", width: 300});
  }
  else
     document.getElementById('button').value='Update image information';
}
function confirmDeleteUser()
{
  var o=document.getElementById('delete');
  if (o.checked)
  {
     Modalbox.show('<div class=\'warning\'><p>Are you sure you want to delete your account and all images you uploaded?  Click \'Update\' to complete the process.</p> <input type=\'button\' value=\'Yes, go ahead\' onclick=\'Modalbox.hide()\' /> or <input type=\'button\' value=\'No, leave it!\' onclick=\'Modalbox.hide();document.getElementById(\"delete\").checked=false;\' /></div>',{title: "Remove your account?", width: 300});
  }
}
function highlight(id,idc)
{
         if (id != "" && document.getElementById(id))  document.getElementById(id).style.border="2px solid red";
         if (idc != "" && document.getElementById(idc)) document.getElementById(idc).src="images/cross.jpg";
}
function lowlight(id,idc)
{
         if (id != "" && document.getElementById(id))  document.getElementById(id).style.border="2px solid grey";
         if (idc != "" && document.getElementById(idc)) document.getElementById(idc).src="images/blank.jpg";
}
function nolight(id,idc)
{
         if (id != ""  && document.getElementById(id))  document.getElementById(id).style.border="0px solid grey";
         if (idc != "" && document.getElementById(idc)) document.getElementById(idc).src="images/blank.jpg";
}

function replaceInput(id,from,to)
{
    var v=document.getElementById(id).value;
    if (v.indexOf(from) > -1) document.getElementById(id).value=v.replace(from,to);
}                                                                                   

function showUploadPreviewImage()
{
  var uploadControl = document.getElementById("image");
  var previewPane=document.getElementById("previewImage");
  var file=uploadControl.value;
  var previewImageHTML="<IMG BORDER=0 HEIGHT=50 SRC='file:///" + escape(file) + "'>";
  previewPane.baseURI="c:\\";
  previewPane.innerHTML=previewImageHTML;
  document.getElementById("123").dir="file://C|/Users/Public/Pictures/Sample%20Pictures/";
}

function validate()
{
   var ok=true;
   var comment="";
   if (document.getElementById('delete').checked) return;

   var id=document.getElementById('price');
   if (id.value == '')
   {
      highlight('price','priceCheck');
      comment = comment + "<li>The <B>price</B> field cannot be left blank.";
      ok=false;
   }
   else
         lowlight('price','priceCheck');


   id=document.getElementById('keywords');
   if (id.value == '')
   {
      highlight('keywords','keywordsCheck');
      comment = comment + "<li>Enter some <B>keywords</B> to make your image more searchable.";
      ok=false;
   }
   else
        lowlight('keywords','keywordsCheck');


   id=document.getElementById('brief');
   if (id.value == '')
   {
      highlight('brief','briefCheck');
      comment = comment + "<li>Enter a <B>brief</B> description of this image.";
      ok=false;
   }
   else
        lowlight('brief','briefCheck');


   if (ok)
   {
      document.forms[0].submit();
      return(true);
   }
   else
   {
     Modalbox.show('<div class=\'warning\'><p>Please check the highlighted fields<BR><UL>' + comment + '</UL></p> <input type=\'button\' value=\'Ok\' onclick=\'Modalbox.hide()\' /></div>',{title: "Oops, some errors were found", width: 300});
     return(false);
   }
}
function validateNewAccount()
{

   //alert("Insert validation routine!");

   if (1==1)
   {


     return(true);
   }
   else
   {
     var comment="";
     Modalbox.show('<div class=\'warning\'><p>Please check the highlighted fields<BR><UL>' + comment + '</UL></p> <input type=\'button\' value=\'Ok\' onclick=\'Modalbox.hide()\' /></div>',{title: "Oops, some errors were found", width: 300});
     return(false);
   }
  return(false);
}

function validateUpload()
{
   var ok=true;
   var comment="";

   id=document.getElementById('author');
   if (id.value == '')
   {
      comment = comment + "<li>Login first";
      ok=false;
     Modalbox.show('<div class=\'warning\'><p>Please check the highlighted fields<BR><UL>' + comment + '</UL></p> <input type=\'button\' value=\'Ok\' onclick=\'Modalbox.hide()\' /></div>',{title: "Oops, some errors were found", width: 300});
   }

   var id=document.getElementById('tandc');
   if (id.checked == false)
   {
      highlight('terms','');
      comment = comment + "<li>Please read and accept the terms and conditions.";
      ok=false;
   }
   else
     nolight('terms','');



   id=document.getElementById('image');
   if (id.value == '')
   {
      highlight('image','imageCheck');
      comment = comment + "<li>Choose an image to upload";
      ok=false;
   }
   else
        lowlightField('image','imageCheck');


   var id=document.getElementById('price');
   if (id.value == '')
   {
      highlight('price','priceCheck');
      comment = comment + "<li>The <B>price</B> field cannot be left blank.";
      ok=false;
   }
   else
         lowlight('price','priceCheck');


   id=document.getElementById('keywords');
   if (id.value == '')
   {
      highlight('keywords','keywordsCheck');
      comment = comment + "<li>Enter some <B>keywords</B> to make your image more searchable.";
      ok=false;
   }
   else
        lowlight('keywords','keywordsCheck');


   id=document.getElementById('brief');
   if (id.value == '')
   {
      highlight('brief','briefCheck');
      comment = comment + "<li>Enter a <B>brief</B> description of this image.";
      ok=false;
   }
   else
        lowlight('brief','briefCheck');

   if (ok)
   {
      document.forms[0].submit();
      return(true);
   }
   else
   {
     Modalbox.show('<div class=\'warning\'><p>Please check the highlighted fields<BR><UL>' + comment + '</UL></p> <input type=\'button\' value=\'Ok\' onclick=\'Modalbox.hide()\' /></div>',{title: "Oops, some errors were found", width: 300});
     return(false);
   }

}

function checkPasswordStrength()
{
   var bar = document.getElementById("passwordQuality");
   var text = document.getElementById("passwordQualityText");
   var pw1= document.getElementById("_password");
   var pw2= document.getElementById("_password2");
   var pwq= document.getElementById("pwquality");

   var col="black";
   var len=0;
   var desc="";
   var score=0;
   
   score = pw1.value.length * 4;
   if (pw1.value.indexOf("0") > -1 ||
   pw1.value.indexOf("1") > -1 ||
   pw1.value.indexOf("2") > -1 ||
   pw1.value.indexOf("3") > -1 ||
   pw1.value.indexOf("4") > -1 ||
   pw1.value.indexOf("5") > -1 ||
   pw1.value.indexOf("6") > -1 ||
   pw1.value.indexOf("7") > -1 ||
   pw1.value.indexOf("8") > -1 ||
   pw1.value.indexOf("9") > -1) score = score * 1.2;
   if (pw1.value.toLowerCase() != pw1) score = score * 1.7;
   if (pw1.value.indexOf("$") > -1 ||
   pw1.value.indexOf("-") > -1 ||
   pw1.value.indexOf("_") > -1 ||
   pw1.value.indexOf(".") > -1 ||
   pw1.value.indexOf(",") > -1 ||
   pw1.value.indexOf("+") > -1 ||
   pw1.value.indexOf("%") > -1 ||
   pw1.value.indexOf("&") > -1 ||
   pw1.value.indexOf("/") > -1 ||
   pw1.value.indexOf("(") > -1 ||
   pw1.value.indexOf(")") > -1 ||
   pw1.value.indexOf("=") > -1 ||
   pw1.value.indexOf("?") > -1 ||
   pw1.value.indexOf(":") > -1 ||
   pw1.value.indexOf(";") > -1) score = score * 1.4;

   if (pw1.value.length < 4) score=10;
   if (pw1.value.length == 0) score=0;

   if (score > 99) score = 100;
   if (score > 90)
   {
      col="green";
      desc="very good";
   }
   if (score < 91)
   {
      col="cyan";
      desc="strong";
   }
   if (score < 75)
   {
      col="yellow";
      desc="good";
   }
   if (score < 50)
   {
      col="orange";
      desc="poor";
   }
   if (score < 10)
   {
      col="red";
      desc="weak";
   }

   if (score > 0)
   {
     bar.style.width=score + "%";
     bar.style.border="2px solid " + col;
     pw1.style.border="2px solid " + col;
     text.innerHTML=desc + " [" + Math.round(score) + "/100]";
   }
   else
   {
     text.innerHTML="";
     bar.style.border="";;
     pw1.style.border="";
     pw2.style.border="";
   }

   if (pw1.value.length == 0) pw1.style.border="";
   if (pw2.value.length == 0) pw2.style.border="";

   if (pw2.value.length > 0 && (pw1.value != pw2.value))
     pw2.style.border="2px dotted red";
   else
     pw2.style.border="";

   pwq.value=Math.round(score);

}

function clearLightBox(id)
{
    cmd="'" + id + "'";
    Modalbox.show('<INPUT TYPE="BUTTON" VALUE="Ok" OnCLICK="killLightbox(' + cmd + ');Modalbox.hide();window.location.reload();window.opener.location.reload();"><INPUT TYPE="BUTTON" VALUE="Cancel" OnClick="Modalbox.hide()">',{title: 'Clear Lightbox', width: 300});
}
function clearLightBoxThere(id)
{
    cmd="'" + id + "'";
    Modalbox.show('<INPUT TYPE="BUTTON" VALUE="Ok" OnCLICK="killLightbox(' + cmd + ');Modalbox.hide();window.location.reload();if (lightbox) lightbox.location.reload();"><INPUT TYPE="BUTTON" VALUE="Cancel" OnClick="Modalbox.hide()">',{title: 'Clear Lightbox', width: 300});
}
function killLightbox(id)
{
  eraseCookie("lightbox--" + id);
  window.location.reload();
}


function checkout()
{
      Modalbox.show('Checkout lets you purchase the images in your lightbox.  Do you want to check out and purchase these images?<INPUT TYPE="BUTTON" VALUE="Yes" OnCLICK="Modalbox.hide();window.opener.location=\'checkout.html\';"><INPUT TYPE="BUTTON" VALUE="Cancel" OnClick="Modalbox.hide()">',{title: 'Checkout?', width: 300});
}
function checkoutThere()
{
      Modalbox.show('Checkout lets you purchase the images in your lightbox.  Do you want to check out and purchase these images?<INPUT TYPE="BUTTON" VALUE="Yes" OnCLICK="Modalbox.hide();window.location.href=\'checkout.html\';"><INPUT TYPE="BUTTON" VALUE="Cancel" OnClick="Modalbox.hide()">',{title: 'Checkout?', width: 300});
}

function showHelp(ob,ob2,ofs)
{
  var helpBox = document.getElementById('helpBox');
  var helpText = document.getElementById('helpText');
  var box = document.getElementById('helpb');
  var y=ofs + document.getElementById(ob2).offsetTop;
  box.style.top= y + "px";
  if (ob.id == "_loginId")     helpText.innerHTML="Choose a login ID.  You will use this when logging into electric-photo.com.  Your login id cannot contain any spaces or punctuation characters but can contain underscores, hyphens and numbers.<BR><I>This is a required entry.</I>";
  if (ob.id == "_displayName") helpText.innerHTML="<BR>Your display name is shown alongside your pictures.  Enter your usual name or author name.  No html or e-mail addresses.<BR><I>This is a required entry.</I>";
  if (ob.id == "_email")       helpText.innerHTML="<BR>Enter your e-mail address.  We will send a confirmation message to this address so ensure you can access it.<BR><I>This is a required entry.</I>";
  if (ob.id == "_password")    helpText.innerHTML="Choose a password.  The quality indicator will show how strong the passwords are.  The stronger the better.  Passwords ARE case sensitive. Good passwords include numbers and a mix of upper and lower case characters.<BR><I>This is a required entry.</I>";
  if (ob.id == "_password2")   helpText.innerHTML="<BR>Re-enter the password to confirm what you entered above. If you see a red-dotted border, the passwords don't yet match.<BR><I>This is a required entry.</I>";
  if (ob.id == "_passwordPrompt") helpText.innerHTML="This password hint should remind you about the password.  We will show this to you if you forget your password so don't make it too revealing.";

  if (ob.id == "_firstname")       helpText.innerHTML="<BR>Enter your first or given name.  You can also add your second name here if you wish.<BR><I>This is a required entry.</I>";
  if (ob.id == "_lastname")       helpText.innerHTML="Enter your family name here.  If you wish to add a suffic such as Sr, Jr or a number like II or III you can add it here.<BR><I>This is a required entry.</I>";
  if (ob.id == "_streetaddress1")       helpText.innerHTML="<BR>Enter the first line of your street address.<BR><I>This is a required entry.</I>";
  if (ob.id == "_streetaddress2")       helpText.innerHTML="<BR><BR>Enter the second line of your street address.";
  if (ob.id == "_city")       helpText.innerHTML="<BR>Enter your city.  If we were able to determine it we already added a suggestion but you can type over it.<BR><I>This is a required entry.</I>";
  if (ob.id == "_stateprov")       helpText.innerHTML="<BR><BR>Enter your e-mail address.  We will send a confirmation message to this address so ensure you can access it.";
  if (ob.id == "_pcode")       helpText.innerHTML="<BR><BR>Enter your full post code (zip code).<BR><I>This is a required entry.</I>";
  if (ob.id == "_stateprov")       helpText.innerHTML="Enter your state, province, canton, region or other information about where your city is within your country. It's ok to leave this field empty if your city doesn't need additional information.";
  if (ob.id == "_country")       helpText.innerHTML="<BR>Enter your country name.  If we were able to determine it we already added a suggestion but you can type over it.<BR><I>This is a required entry.</I>";
  if (ob.id == "_homephone")       helpText.innerHTML="<BR>If you wish, give us a telephone number that we can contact you on if we need to.";

  if (ob.id == "_paypalid")       helpText.innerHTML="<BR>We need your PayPal ID so we can transfer funds to you when your images are sold.<BR>If you're not sure of this now, you can update it later.";

  helpBox.style.minHeight="80px";

}



function store(ob)
{
  //store session only cookie for this field value
  createCookie(ob.id,getFieldValue(ob));

}
function restore(ob)
{
  //restore session only cookie for this field value if it exists
  var x = readCookie(ob.id);
  if (x != "" && x != null && ob.value == "") ob.value=x;
}
function restoreAllfields()
{
         var doc = document.getElementsByTagName('*');
         for (var i = 0; i < doc.length; i++)
         {
             restore(doc[i]);
         }
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	//if (readCookie(name) != value) alert("cookie failure: " + name);
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function refreshParent() {
  window.opener.location.href = window.opener.location.href;
  window.close();
}


function addImageToLightbox(id,login)
{
    window.open('updateLightbox.php?f=add&id=' + id,'_update','height=1,width=1');
    //alert("ADD id=" + id + ", login=" + login);
    var cv = readCookie("lightbox--" + login);
    if (cv == "" | cv == null)
    {
      cv=id;
    }
    else
    {
      var after = cv.split(",");
      after = after.concat(id);
      cv =  after.join(",");
    }
    createCookie("lightbox--" + login,cv,30);
    refreshLightBox();
    setLightBoxOptions(id,login);
    location.reload();
}
function removeImageFromLightbox(id,login)
{
     window.open('updateLightbox.php?f=remove&id=' + id,'_update','height=1,width=1');
   //alert("REMOVE id=" + id + ", login=" + login);
    var cv = readCookie("lightbox--" + login);
    if (cv == null) return;
    if (cv != "")
    {
    var after = new Array();
    bits = cv.split(",");
    for (var i=0; i < bits.length; i++)
    {
      if (bits[i] != id && bits[i] != ",")
      {
        after = after.concat(bits[i]);
      }
    }
    cv =  after.join(",");
    createCookie("lightbox--" + login,cv,30);
    }
    refreshLightBox();
    setLightBoxOptions(id,login);
    location.reload();
}

function getLightBox(id)
{
   contents = readCookie("lightbox--" + id);
   if (contents == null) return;
   html="";
   if (contents != "")
   {
     bits = contents.split(",");
     for (var i=0; i < bits.length; i++)
     {
        if (bits[i] != "")
        {
          html = html + "<IMG SRC='" + bits[i] + "' BORDER=0 STYLE=''>";
        }
     }
   }
   return(html);
}

function showLightBox(login)
{
   contents = readCookie("lightbox--" + login);
   if (contents == null) return;
   if (contents != "")
   {
     lightbox=window.open('lightbox.html','lightbox','width=700,height=80,scrollbars=no,toolbar=no,menubar=no,resizable=no');
   }
}

function refreshLightBox()
{
   try
   {
      if (lightbox != null) lightbox.window.location.reload();
   }
   catch (e)
   {
   }
}

function setLightBoxOptions(id,login)
{
        if (login == "") return;
        if(document.getElementById("lightbox-link") == null) return;
        contents = readCookie("lightbox--" + login);
        if (contents == null)
        {
  	  var link="<img src='/images/add.gif' border=0 title='Add this image to your current lightbox' onClick=\"popup=addImageToLightbox('" + id  + "','" + login + "');\">";
          document.getElementById("lightbox-link").innerHTML=link;
          document.getElementById("lightbox-text").innerHTML="<A HREF='#' onClick=\"popup=addImageToLightbox('" + id  + "','" + login + "');\">Add to your light box</A>";
        }

        try
        {
        if (contents.indexOf(id) > -1)
        {
	 var link="<img src='/images/minuscolour.gif' border=0 title='Remove this image from your current lightbox' onClick=\"removeImageFromLightbox('" + id  + "','" + login + "');\">";
         document.getElementById("lightbox-link").innerHTML=link;
         document.getElementById("lightbox-text").innerHTML="<A HREF='#' onClick=\"removeImageFromLightbox('" + id  + "','" + login + "');\">Remove from your light box</A>";
       }
       else
       {
   	 var link="<img src='/images/add.gif' border=0 title='Add this image to your current lightbox' onClick=\"popup=addImageToLightbox('" + id  + "','" + login + "');\">";
         document.getElementById("lightbox-link").innerHTML=link;
         document.getElementById("lightbox-text").innerHTML="<A HREF='#' onClick=\"popup=addImageToLightbox('" + id  + "','" + login + "');\">Add to your light box</A>";
       }
        if (contents.length > 1)
        {
	 var link="<img src='/images/folder.gif' border=0 title='Show the lightbox' onClick='lightboxToggle(\"" + id + "\");'>";
         document.getElementById("lightbox-toggle-link-icon").innerHTML=link;
         document.getElementById("lightbox-toggle-link-text").innerHTML="<A HREF='#' onClick='lightboxToggle(\"" + id + "\");'>Show lightbox</A>";
       }
        }
        catch (e)
        {
        }

}

function lightboxToggle(login)
{
  if (lightbox == null || lightbox == undefined || lightbox.window.closed)
  {
    showLightBox(login);
  }
  else
  {
     lightbox.close();
  }
}

function saveXY()
{
  createCookie("lightbox-SizeX",window.outerWidth,30);
  createCookie("lightbox-SizeY",window.outerHeight,30);
  createCookie("lightbox-PositionX",window.screenX,30);
  createCookie("lightbox-PositionY",window.screenY,30);
}


function setSize(lightbox)
{
  var x=readCookie("lightbox-SizeX");
  var y=readCookie("lightbox-SizeY");
  if (x == 0 || x == null || x == undefined) x = getX();
  if (y == 0 || y == null || y == undefined) y = getY();
     if (x < 500)
     {
       x=500;
     }
     if (y < 200)
     {
       y=200;
     }
     lightbox.resizeTo(x,y);
     createCookie("lightbox-SizeX",x,30);
     createCookie("lightbox-SizeY",y,30);

  var xp=readCookie("lightbox-PositionX");
  var yp=readCookie("lightbox-PositionY");
  if (xp == 0 || xp == undefined) xp = 100;
  if (yp == 0 || yp == undefined) yp = 100;
     lightbox.moveTo(xp,yp);
     createCookie("lightbox-PositionX",xp,30);
     createCookie("lightbox-PositionY",yp,30);
}

function getX()
{
  return(window.outerWidth);
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return(myWidth);
}
function getY()
{
  return(window.outerHeight);
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return(myHeight);
}


function drag()
{
  alert("Drag");
}

function showSample(watermark,sample,obj)
{
  var b=document.getElementById(obj).src;
  //swap betweeen the watermark and the sample image
  if (b.endsWith(watermark))
  {
    document.getElementById(obj).src=sample;
  }
  else
  {
    document.getElementById(obj).src=watermark;
  }
}
function showWatermark(watermark,sample,obj)
{
    document.getElementById(obj).src=watermark;
}


function removeImageFromLibrary(id)
{
    cmd="'" + id + "'";
    Modalbox.show('If you remove this image it will no longer be available for you to download.  Your rights to use the image according to the original licese are uneffected but if you wish to download it again you will need to re-purchase it.<BR><BR><INPUT TYPE="BUTTON" VALUE="Yes, Remove it" OnCLICK="removeFromLibrary(' + cmd + ');Modalbox.hide();window.location.reload();window.opener.location.reload();"><INPUT TYPE="BUTTON" VALUE="No, please leave it" OnClick="Modalbox.hide()">',{title: 'Remove this image from your library of purchases?', width: 300});
}

function removeFromLibrary(id)
{
  window.open('removeFromLibrary.html?id=' + id,'','height=1,width=1');
}

// **************************************************************************************************************



String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}




function dumpProps(objName)
 {
var isNav = (navigator.appName == "Netscape")
var obj = eval(objName)
var msg = ""
var count = 0
var maxProps = 10
// Loop through properties of the object
for (var i in obj) {
if (i != "outerHTML" && i != "outerText" && i != "innerHTML" && i
!= "innerText" && i != "domain") {
msg += objName + "." + i + "=" + obj[i] + "<BR>"
if (count > maxProps) {
// Output a batch
if (isNav) {
document.write(msg)
}
else {
alert(msg)
}
msg = ""
count = 0
continue
}
count++
}
}
// Output any leftovers
if (isNav) {
document.write(msg)
} else {
alert(msg)
}
}


/**************************************************
 * dom-drag.js
 * 09.25.2001
 * www.youngpup.net
 * Script featured on Dynamic Drive (http://www.dynamicdrive.com) 12.08.2005
 **************************************************
 * 10.28.2001 - fixed minor bug where events
 * sometimes fired off the handle, not the root.
 **************************************************/

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]),
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
 }


 // **************************************************************************
// Copyright 2007 - 2008 The JSLab Team, Tavs Dokkedahl
// Contact: http://www.jslab.dk/contact.php
//
// This file is part of the JSLab Standard Library (JSL) Program.
//
// JSL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// any later version.
//
// JSL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ***************************************************************************

// Return new array with duplicate values removed
Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) {
        // If this[i] is found later in the array
        if (this[i] === this[j])
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };
// Compute the intersection of n arrays
Array.prototype.intersect =
  function() {
    if (!arguments.length)
      return [];
    var a1 = this;
    var a = a2 = null;
    var n = 0;
    while(n < arguments.length) {
      a = [];
      a2 = arguments[n];
      var l = a1.length;
      var l2 = a2.length;
      for(var i=0; i<l; i++) {
        for(var j=0; j<l2; j++) {
          if (a1[i] === a2[j])
            a.push(a1[i]);
        }
      }
      a1 = a;
      n++;
    }
    return a.unique();
  };
  
  // Get the union of n arrays
Array.prototype.union =
  function() {
    var a = [].concat(this);
    var l = arguments.length;
    for(var i=0; i<l; i++) {
      a = a.concat(arguments[i]);
    }
    return a.unique();
  };
  

// Return elements which are in A but not in arg0 through argn
Array.prototype.diff =
  function() {
    var a1 = this;
    var a = a2 = null;
    var n = 0;
    while(n < arguments.length) {
      a = [];
      a2 = arguments[n];
      var l = a1.length;
      var l2 = a2.length;
      var diff = true;
      for(var i=0; i<l; i++) {
        for(var j=0; j<l2; j++) {
          if (a1[i] === a2[j]) {
            diff = false;
            break;
          }
        }
        diff ? a.push(a1[i]) : diff = true;
      }
      a1 = a;
      n++;
    }
    return a.unique();
  };

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}


Array.prototype.remove=function(s)
{
  var i = this.indexOf(s);
  if(i != -1) this.splice(i, 1);
}

Array.prototype.asString=function(sep)
{
  var tmp="";
  if (sep=="" | sep==null | sep == undefined) sep=";";
  for (var t=0; t < this.length; t++)
  {
    tmp = tmp + this[t];
    if (t != this.length-1) tmp = tmp + sep;
  }
  return(tmp);
}

function getFieldValue(field)
{
  if (field.type == undefined) return null;
   switch(field.type)
   {
      case "text" :
      case "textarea" :
      case "password" :
      case "hidden" :
         return field.value;

      case "select-one" :
         var i = field.selectedIndex;
         if (i == -1)   return "";
         else   return (field.options[i].value == "") ? field.options[i].text : field.options[i].value;

      case "select-multiple" :
         var allChecked = new Array();
         for(i = 0; i < field.options.length; i++)
            if(field.options[i].selected)
               allChecked[allChecked.length] = (field.options[i].value == "") ? field.options[i].text : field.options[i].value;
         return allChecked;

      case "button" :
      case "reset" :
      case "submit" :
         return "";

      case "radio" :
      case "checkbox" :
         if (field.checked) { return field.value; } else { return ""; }
      default :
         if(field[0].type == "radio")
         {
            for (i = 0; i < field.length; i++)
               if (field[i].checked)
                  return field[i].value;

            return "";
         }
         else if(field[0].type == "checkbox")
         {
            var allChecked = new Array();
            for(i = 0; i < field.length; i++)
               if(field[i].checked)
                  allChecked[allChecked.length] = field[i].value;

            return allChecked;
         }
         else
            var str = "";
            for (x in field) { str += x + "\n"; }
            alert("I couldn't figure out what type this field is...\n\n" + field.name + ": ???\n\n\n" + str + "\n\nlength = " + field.length);
         break;
   }

   return "";
}

function setFieldValue(field,val)
{
   switch(field.type)
   {
      case "text" :
      case "textarea" :
      case "password" :
      case "hidden" :
         field.value=val;

      case "select-one" :
         var i = field.selectedIndex;
         if (i == -1)   return "";
         else   return (field.options[i].value == "") ? field.options[i].text : field.options[i].value;

      case "select-multiple" :
         var allChecked = new Array();
         for(i = 0; i < field.options.length; i++)
            if(field.options[i].value == val)
            {
              field.options[i].selected = true;
            }
            else
              field.options[i].selected = false;
         return;

      case "button" :
      case "reset" :
      case "submit" :
      case "radio" :
      case "checkbox" :
         field.value=val;
      default :
         if(field[0].type == "radio")
         {
            for (i = 0; i < field.length; i++)
               if (field[i].value == val)
                  field[i].checked = true;
            return;
         }
         else if(field[0].type == "checkbox")
         {
            var allChecked = new Array();
            for(i = 0; i < field.length; i++)
               if(field[i].checked)
                  allChecked[allChecked.length] = field[i].value;

            return allChecked;
         }
         else
            var str = "";
            for (x in field) { str += x + "\n"; }
            alert("I couldn't figure out what type this field is...\n\n" + field.name + ": ???\n\n\n" + str + "\n\nlength = " + field.length);
         break;
   }

   return "";
}


function downloadImage(id)
{
  window.open('getImage.php?id=' + id,'download','width=1,height=1,scrollbars=no,status=no');
}

function validateContact()
        {
           //Check the question
           if (SHA1(getSelectionValue('CHOICES0') + document.getElementById("ID").value)==document.getElementById("SIGNATURE").value)
             return(true);
           else
           {
             cc++;
             if (cc > 2)
             {
               alert("Sorry. Try completing the form again.");
               window.close();
             }
             else
             {
               alert("Sorry, the answer to the question is incorrect. Please try again.");
               return(false);
             }
           }
         }


/**
*
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*
**/

function SHA1 (msg) {

    function rotate_left(n,s) {
        var t4 = ( n<<s ) | (n>>>(32-s));
        return t4;
    };

    function lsb_hex(val) {
        var str="";
        var i;
        var vh;
        var vl;

        for( i=0; i<=6; i+=2 ) {
            vh = (val>>>(i*4+4))&0x0f;
            vl = (val>>>(i*4))&0x0f;
            str += vh.toString(16) + vl.toString(16);
        }
        return str;
    };

    function cvt_hex(val) {
        var str="";
        var i;
        var v;

        for( i=7; i>=0; i-- ) {
            v = (val>>>(i*4))&0x0f;
            str += v.toString(16);
        }
        return str;
    };


    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var blockstart;
    var i, j;
    var W = new Array(80);
    var H0 = 0x67452301;
    var H1 = 0xEFCDAB89;
    var H2 = 0x98BADCFE;
    var H3 = 0x10325476;
    var H4 = 0xC3D2E1F0;
    var A, B, C, D, E;
    var temp;

    msg = Utf8Encode(msg);

    var msg_len = msg.length;

    var word_array = new Array();
    for( i=0; i<msg_len-3; i+=4 ) {
        j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
        msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
        word_array.push( j );
    }

    switch( msg_len % 4 ) {
        case 0:
            i = 0x080000000;
        break;
        case 1:
            i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
        break;

        case 2:
            i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
        break;

        case 3:
            i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8    | 0x80;
        break;
    }

    word_array.push( i );

    while( (word_array.length % 16) != 14 ) word_array.push( 0 );

    word_array.push( msg_len>>>29 );
    word_array.push( (msg_len<<3)&0x0ffffffff );


    for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {

        for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
        for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);

        A = H0;
        B = H1;
        C = H2;
        D = H3;
        E = H4;

        for( i= 0; i<=19; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=20; i<=39; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=40; i<=59; i++ ) {
            temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        for( i=60; i<=79; i++ ) {
            temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
            E = D;
            D = C;
            C = rotate_left(B,30);
            B = A;
            A = temp;
        }

        H0 = (H0 + A) & 0x0ffffffff;
        H1 = (H1 + B) & 0x0ffffffff;
        H2 = (H2 + C) & 0x0ffffffff;
        H3 = (H3 + D) & 0x0ffffffff;
        H4 = (H4 + E) & 0x0ffffffff;

    }

    var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);

    return temp.toLowerCase();

}

       function getSelectionValue(id)
       {
       	  var dropdownIndex = document.getElementById(id).selectedIndex;
          return(document.getElementById(id).options[dropdownIndex].text);

       }

       function resetLoginCookies()
       {
          eraseCookie("EP-LoginID");
          eraseCookie("EP-LoginPW");
          location.href="login.html";
       }



function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

function shiftOpacity(id, millisec) {
    //if an element is invisible, make it visible, else make it ivisible
    if(document.getElementById(id).style.opacity == 0) {
        opacity(id, 0, 100, millisec);
    } else {
        opacity(id, 100, 0, millisec);
    }
} 
function currentOpac(id, opacEnd, millisec) {
    //standard opacity is 100
    var currentOpac = 100;

    //if the element has an opacity set, get it
    if(document.getElementById(id).style.opacity < 100) {
        currentOpac = document.getElementById(id).style.opacity * 100;
    }

    //call for the function that changes the opacity
    opacity(id, currentOpac, opacEnd, millisec)
}
function blendimage(divid, imageid, imagefile, millisec) {
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //set the current image as background
    document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")";

    //make image transparent
    changeOpac(0, imageid);

    //make new image
    document.getElementById(imageid).src = imagefile;

    //fade in image
    for(i = 0; i <= 100; i++) {
        setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed));
        timer++;
    }
}

function swapBannerImage()
{
  var image=document.getElementById('BANNER_IMAGE');
  if (image.src == 'http://www.electric-photo.com/images/banner4.jpg')
  {
     blendimage("BANNER_IMAGE_DIV", "BANNER_IMAGE", "images/banner5.jpg", 1000);
     return;
  }
  if (image.src == 'http://www.electric-photo.com/images/banner5.jpg')
  {
    blendimage("BANNER_IMAGE_DIV", "BANNER_IMAGE", "images/banner6.jpg", 1000);
    return;
  }
  if (image.src == 'http://www.electric-photo.com/images/banner6.jpg')
  {
     blendimage("BANNER_IMAGE_DIV", "BANNER_IMAGE", "images/banner7.jpg", 1000);
     return;
  }
  if (image.src == 'http://www.electric-photo.com/images/banner7.jpg')
  {
    blendimage("BANNER_IMAGE_DIV", "BANNER_IMAGE", "images/banner8.jpg", 1000);
    return;
  }
  if (image.src == 'http://www.electric-photo.com/images/banner8.jpg')
  {
    blendimage("BANNER_IMAGE_DIV", "BANNER_IMAGE", "images/banner9.jpg", 1000);
    return;
  }

  if (image.src == 'http://www.electric-photo.com/images/banner9.jpg')
  {
    blendimage("BANNER_IMAGE_DIV", "BANNER_IMAGE", "images/banner4.jpg", 1000);
    return;
  }
}


function setup()
{
   var defaultImage="dcrocker_1fbe125f.jpg";

   var results = document.getElementsByName("imageResult");
   for (var x=0; x < results.length; x++)
   {
     descriptions[x]=document.getElementById("imageBrief-" + x).value;
   }
   var size=readCookie('<?php echo $login ."-searchResultThumbSize"; ?>');
   if (size < 50 | size > 500 | size == null | size == undefined) size=200;
   resize(size);

}
function bigger()
{
   var size=readCookie('<?php echo $login ."-searchResultThumbSize"; ?>');
   size = parseInt(size * 1.3);
   if (size > 300) size = 300;
   createCookie('<?php echo $login ."-searchResultThumbSize"; ?>',size,30);
   resize(size);
}
function smaller()
{
   var size=readCookie('<?php echo $login ."-searchResultThumbSize"; ?>');
   size = parseInt(size / 1.3);
   if (size < 50) size = 50;
   createCookie('<?php echo $login ."-searchResultThumbSize"; ?>',size,30);
   resize(size);
}
function resize(size)
{
   var results = document.getElementsByName("imageResult");
   for (var x=0; x < results.length; x++)
   {
     var containers=document.getElementById("container-" + x);
     var imageBoxes=document.getElementById("imageBox-" + x);
     var images=document.getElementById("image-" + x);
     var imageText=document.getElementById("imageText-" + x);
     if (containers)
     {
      containers.style.minHeight=size;
      containers.style.width=size;
      //imageBoxes.style.minHeight=size;
      images.width=size;
      if (imageText)
      {
        imageText.style.fontSize=size/10 + "px";
        if (size < 1)
          imageText.innerHTML=""
        else
          imageText.innerHTML=descriptions[x];
      }
     }
   }
}

function checkRequiredFields()
{
  var state=0;


  var x=document.getElementById('location');
  var c=document.getElementById('locationCheck');
  if (getFieldValue(x) == '')
  {
    c.src="images/infocolour.gif";
  }
  else
    c.src="images/blank.jpg";

  var x=document.getElementById('quality');
  var c=document.getElementById('qualityCheck');
  if (getFieldValue(x) == '')
  {
    c.src="images/cross.gif";
    state=1;
  }
  else
    c.src="images/blank.jpg";

  var x=document.getElementById('price');
  var c=document.getElementById('priceCheck');
  if (getFieldValue(x) == '')
  {
    c.src="images/cross.gif";
    state=1;
  }
  else
    c.src="images/blank.jpg";

  var x=document.getElementById('brief');
  var c=document.getElementById('briefCheck');
  if (getFieldValue(x) == '')
  {
    c.src="images/cross.gif";
    state=1;
  }
  else
    c.src="images/blank.jpg";


  var x=document.getElementById('keywords');
  var c=document.getElementById('keywordsCheck');
  if (getFieldValue(x) == '')
  {
    c.src="images/infocolour.gif";
  }
  else
    c.src="images/blank.jpg";


  return(state);
}

function toggleCS(ob)
{
  if (ob.style.backgroundColor=='orange')
  {
     ob.style.backgroundColor="black";
  }
  else
  {
     ob.style.backgroundColor="orange";
  }

  //run through all the ssuares and build up the field value
  var cs="";
  if (document.getElementById('cs11').style.backgroundColor=="orange") cs=cs + "11;";
  if (document.getElementById('cs12').style.backgroundColor=="orange") cs=cs + "12;";
  if (document.getElementById('cs13').style.backgroundColor=="orange") cs=cs + "13;";
  if (document.getElementById('cs14').style.backgroundColor=="orange") cs=cs + "14;";

  if (document.getElementById('cs21').style.backgroundColor=="orange") cs=cs + "21;";
  if (document.getElementById('cs22').style.backgroundColor=="orange") cs=cs + "22;";
  if (document.getElementById('cs23').style.backgroundColor=="orange") cs=cs + "23;";
  if (document.getElementById('cs24').style.backgroundColor=="orange") cs=cs + "24;";

  if (document.getElementById('cs31').style.backgroundColor=="orange") cs=cs + "31;";
  if (document.getElementById('cs32').style.backgroundColor=="orange") cs=cs + "32;";
  if (document.getElementById('cs33').style.backgroundColor=="orange") cs=cs + "33;";
  if (document.getElementById('cs34').style.backgroundColor=="orange") cs=cs + "34;";

  if (document.getElementById('cs41').style.backgroundColor=="orange") cs=cs + "41;";
  if (document.getElementById('cs42').style.backgroundColor=="orange") cs=cs + "42;";
  if (document.getElementById('cs43').style.backgroundColor=="orange") cs=cs + "43;";
  if (document.getElementById('cs44').style.backgroundColor=="orange") cs=cs + "44;";

  document.getElementById('copyarea').value=cs;
}

function setCopyArea(set)
{
   var x=set.split(";");
   for(p=0; p < x.length; p++)
   {
     document.getElementById('cs' + x[p]).style.backgroundColor="orange";
   }
   document.getElementById('copyarea').value=set;
}

function mailit(id)
{
 window.open('mailit.html?id=' + id,'mailit','directories=no,copyhistory=no,menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,height=700,width=610');
}

function checkEmailAddress()
{
   // 0 = no valid email address
   // 1 = ok to send

   var e=document.getElementById('emailaddress');
   var i=document.getElementById('emailcheck');
   var b=document.getElementById('send');
   var r=0;
   var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
   if (e.value.search(emailRegEx) == -1)
   {
          r=1;
   }
   if (r==1)
   {
     i.src="images/cross.gif";
     b.disabled=true;
   }
   else
   {
     i.src="images/empty.gif";
     b.disabled=false;
   }
   return(r);
}

function histView(f)
{
document.getElementsByName('wmark')[0].src='lib/phpThumb/phpThumb.php?src=../../' + f + '&fltr[]=hist|rgb||||BR|100&fltr[]=hist|*||||BL|100';
hit=hit+1;
if (hit == 2)
{
  document.getElementById('histMessage').innerHTML="Not ready yet... please be patient.";
  alert("Please be patient, the histogram takes a while to create.  Subsequent loads will be much faster");
}
if (hit < 2)
{
  document.getElementById('histMessage').innerHTML="Histogram is being generated... please be patient can take a minute or so.";
}
}
function histClear()
{
document.getElementsByName('wmark')[0].src=preview;
document.getElementById('histMessage').innerHTML="";
}

function removeSelectedFromLightbox()
{
  //check for objects with "remove-nn"  and create a request to the updateLightbox.php?f=reduce  command with each ID specified
  var items = document.getElementsByTagName('input');
  var tmp="";
       for (var k=0; k < items.length; k++)
        {
          if (items[k].id.startsWith("remove-") && items[k].checked)
          {
           tmp = tmp + items[k].name + ",";
         }
        }
        if (tmp != "")
        {
          window.open('updateLightbox.php?f=reduce&ids=' + tmp,'','height=1,width=1');
          location.reload();
        }
}
function searchByURL()
{

  //Formulate a search query using the fields  searchbar, scope and order
  var query=escape(getFieldValue(document.getElementById('searchbar')));
  var scope=escape(getFieldValue(document.getElementById('scope')));
  var order=getFieldValue(document.getElementById('order'));
  var direction=getFieldValue(document.getElementById('direction'));

  url="viewBy.html?scope=" + scope + "&opt=multi&order=" + order + "&direction=" + direction + "&f=" + query;
  window.location.href=url;

}

function searchBarButton()
{
  var f=getFieldValue(document.getElementById('searchbar'));
 if (f == null || f == '' || f == 'enter search words')
 {
    window.location.href='search.html';
    return(false);
 }
 else
 {
    searchByURL();
 }
}

function initMap(lat,lng,zoom,interactive)
{
    if (lat=="") lat=47.0;
    if (lng=="") lng=8.5;
    if (zoom=="") zoom=13;

   if (lat != "" && GBrowserIsCompatible()) {
    // define the crosshair tile layer and its required functions
    var crossLayer = new GTileLayer(new GCopyrightCollection(""), 0, 15);
    crossLayer.getTileUrl =  function(tile, zoom) {
      return "./include/tile_crosshairs.png";
    }
    crossLayer.isPng = function() {return true;}

    var center = new GLatLng(lat, lng);
    // Create a new map type incorporating the tile layer
    var layerTerCross = [ G_PHYSICAL_MAP.getTileLayers()[0],
                          crossLayer ];
    var mtTerCross = new GMapType(layerTerCross,
                                  G_PHYSICAL_MAP.getProjection(), "Ter+");

    var map = new GMap2(document.getElementById("map_canvas"),
        { size: new GSize(900,500) } );
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_HYBRID_MAP);
    map.addMapType(mtTerCross);
    map.setCenter(center,zoom);
    map.addControl(new GLargeMapControl())

    if (interactive == true)
    {
        map.openInfoWindow(map.getCenter(), document.createTextNode("Enter a location above, or drag and drop this marker to the location you want to assign to the image. As you move the marker, the location data is changed in the image.  Close this window and then press 'Update image information' to save the changes."));

        var marker = new GMarker(center, {draggable: true});

        GEvent.addListener(marker, "dragstart", function() {
          map.closeInfoWindow();
        });

        GEvent.addListener(marker, "dragend", function() {
          map.setCenter(marker.getLatLng(),map.getZoom());
          var lat=map.getCenter().lat();
          var lng=map.getCenter().lng();
          var zoom2=map.getZoom();
          var update='updateMap(' + lat + ',' + lng + ',' + zoom2 + ');';
          updateMap(lat,lng,zoom2);
          //marker.openInfoWindowHtml("Set coordinates to<BR>Latitude: " + lat + "<BR>Longitude: " + lng + "<BR><BR>Map Zoom Level: " + zoom2 + "<BR><BR><A HREF='#' onClick='" + update + "'>Click here to set this as the location</A>");
          marker.openInfoWindowHtml("Set coordinates to<BR><BR>Latitude: " + lat + "<BR>Longitude: " + lng + "<BR><BR>Map Zoom Level: " + zoom2);
        });

        GEvent.addListener(map, "dragend", function() {
          map.closeInfoWindow();
          marker.setLatLng(map.getCenter());
        });
    }
    else
    {
        var marker = new GMarker(center, {draggable: false});
    }
    map.addOverlay(marker);

    var mapControl = new GHierarchicalMapTypeControl();

    // Set up map type menu relationships
    mapControl.clearRelationships();
    //mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
    mapControl.addRelationship(G_PHYSICAL_MAP, mtTerCross, "Crosshairs");

    // Add control after you've specified the relationships
    map.addControl(mapControl);
    geocoder = new GClientGeocoder();

    return(map);

  }
}

function showAddress(address,map)
{
      if (geocoder)
      {
        geocoder.getLatLng(
          address,
          function(point)
          {
            if (!point)
            {
              alert("Sorry, couldn't find " + address + ".  Please try again.");
            }
            else
            {
              map.setCenter(point, 13);
              var marker = new GMarker(point);
              map.addOverlay(marker);
              marker.openInfoWindowHtml(address);
            }
          }
        );
      }
}

function updateMap(lat,lng,zoom)
{
  window.opener.document.getElementById('latitude').value=lat;
  window.opener.document.getElementById('longitude').value=lng;
  window.opener.document.getElementById('mapZoom').value=zoom;
  createCookie("ep-lastgeo-lat",lat,10);
  createCookie("ep-lastgeo-lng",lng,10);
  createCookie("ep-lastgeo-zoom",zoom,10);
}

function updateMap2()
{
         var lat=map.getCenter().lat();
         var lng=map.getCenter().lng();
         var zoom2=map.getZoom();
         var update='updateMap(' + lat + ',' + lng + ',' + zoom2 + ');';
         updateMap(lat,lng,zoom2);
}

function quickEdit(ob,id)
{
       v=document.getElementById(ob).value;
       if (ob.indexOf('DESCRIPTION') > -1) window.open('quickedit.html?id='+ id + '&description=' + escape(v),"quickEdit","height=200,width=200");
       if (ob.indexOf('PRICE') > -1) window.open('quickedit.html?id='+ id + '&price=' + escape(v),"quickEdit","height=200,width=200");
       if (ob.indexOf('KEYWORDS') > -1) window.open('quickedit.html?id='+ id + '&keywords=' + escape(v),"quickEdit","height=200,width=200");

}