function roundStuff ()
{
//    roundClass(null, "round", null);
//    roundClass(null, "round_top", {'corners': 'tl tr'});
//    roundClass(null, "round_bottom", {'corners': 'bl br'});
//    roundClass(null, "round_ccc", {'bgColor': '#CCC'});
//    roundClass(null, "round_top_ccc", {'bgColor': '#CCC', 'corners': 'tl tr'});
//    roundClass(null, "round_bottom_ccc", {'bgColor': '#CCC', 'corners': 'bl br'});
//    roundClass(null, "round_ddd", {'bgColor': '#DDD'});
   $('.round').corner({autoPad:true, antiAlias:true});
   $('.round_top').corner({autoPad:true, antiAlias:true, bl: false, br: false});
   $('.round_bottom').corner({autoPad:true, antiAlias:true, tl: false, tr: false});
   $('.round_ccc').corner({autoPad:true, antiAlias:true});
   $('.round_top_ccc').corner({autoPad:true, antiAlias:true, bl: false, br: false});
   $('.round_bottom_ccc').corner({autoPad:true, antiAlias:true, tl: false, tr: false});
   $('.round_ddd').corner({autoPad:true, antiAlias:true});
}

function showAdvSearch ()
{
    document.advSearch.searchDisplay.value = 'A';
    document.getElementById('searchAction').value = 'advSearch';
    document.advSearch.submit();

//    document.getElementById('advSearch1').style.display = 'block';
//    document.getElementById('advSearch2').style.display = 'block';
//    document.getElementById('searchDisplay').value = 'A';
//    document.getElementById('searchAction').value = 'advSearch';
//    document.getElementById('advLink').style.color = '#00F';
//    document.getElementById('simpleLink').style.color = '#FFF';
//    document.getElementById('mainSearchTable').style.height = '120px';
}

function hideAdvSearch ()
{
    document.getElementById('advSearch1').style.display = 'none';
    document.getElementById('advSearch2').style.display = 'none';
    document.getElementById('searchDisplay').value = 'S';
    document.getElementById('searchAction').value = 'simpleSearch';
    document.advSearch.submit();
//    document.getElementById('searchDisplay').value = 'S';
//    document.getElementById('searchAction').value = 'simpleSearch';
//    document.getElementById('advLink').style.color = '#FFF';
//    document.getElementById('simpleLink').style.color = '#00F';
//    document.getElementById('mainSearchTable').style.height = '45px';
}

var pdfIds = '';

function show_pp (idString)
{
    idString = idString.substring(0, idString.length - 1);
    pdfIds = idString;
    window.open('printproof.php', 'PrintProof', 'width=600,height=600,scrollbars=1');
}

function PrevImage (increment)
{
    if (myImg != myImages[0][0])
    {
        for (var i = 0; i < myImages.length; i++)
        {
            if (myImg == myImages[i][0])
            {
                if(i-increment < 0) { return; }
                myImg = myImages[i - increment][0];
                myImgName = myImages[i - increment][2];
                break;
            }
        }
        
        updateViewChkBx(myImg);
        
        document.getElementById('LargeImg').src = "sales_image.php?name=" + myImgName + "&id=" + myImg + "&lb=" + myLbx + "&size=medium";
        
        document.getElementById('NextImage').style.display = 'inline';
        
        if (myImg == myImages[0][0])
        {
            document.getElementById('PrevImage').style.display = 'none';
        }
        
        updateLVButtons(myImg);
        updateMetadata(i-increment);
        updateFilmstrip(i-increment, increment);
    }
}

function NextImage (increment)
{
    if (myImg != myImages[myImages.length - 1][0])
    {
        for (var i = 0; i < myImages.length; i++)
        {
            if (myImg == myImages[i][0])
            {
                if(i+increment >= myImages.length) { return; }
                myImg = myImages[i + increment][0];
                myImgName = myImages[i + increment][2];
                break;
            }
        }
        
        updateViewChkBx(myImg);
        
        document.getElementById('LargeImg').src = "sales_image.php?name=" + myImgName + "&id=" + myImg + "&lb=" + myLbx + "&size=medium";
        
        document.getElementById('PrevImage').style.display = 'inline';
        
        if (myImg == myImages[myImages.length - 1][0])
        {
            document.getElementById('NextImage').style.display = 'none';
        }
        
        updateLVButtons(myImg);
        updateMetadata(i+increment);        
        updateFilmstrip(i+increment, increment);

    }
}

function updateFilmstrip(index, increment)
{
   var j;
   var parent = document.getElementById('filmstrip');
   for(j = 0;j < increment; ++j)
   {
      var first = document.getElementById('filmstrip_box_0');
      
      parent.removeChild(first);
      parent.appendChild(first);
      
      var children = parent.childNodes;
      var count = 0;
      for(k = 0; k < children.length; k++)
      {
         if (children[k].nodeName == 'DIV')
         {
            children[k].id = 'filmstrip_box_' + count;
            children[k].getElementsByTagName('IMG')[0].id = 'filmstrip_' + count;
            
            ++count;
         } 
      }
   }

   var i;
   for(i = 0; i < 7; ++i)
   {
      var img = document.getElementById('filmstrip_' + i);
      var box = document.getElementById('filmstrip_box_' + i);
      
      
      if(i == 0 || i == 6)
      {
         box.style.visibility = "hidden";
         box.style['filter'] = "alpha(opacity=0)";
      }
      else
      {
         box.style.visibility = "visible";
         box.style['filter'] = "";
      }
      
      var pos = index - 3 + i;
      
      if (pos >= 0 && pos < myImages.length)
      {
         if(i == 0 || i == 6)
         {
            img.src = "sales_image.php?name=" + myImages[pos][2] + "&id=" + myImages[pos][0] + "&lb=" + myLbx + "&size=small";
         }
         else if(img.src != "sales_image.php?name=" + myImages[pos][2] + "&id=" + myImages[pos][0] + "&lb=" + myLbx + "&size=small")
         {
            img.src = "sales_image.php?name=" + myImages[pos][2] + "&id=" + myImages[pos][0] + "&lb=" + myLbx + "&size=small";
         }
         
         if(myImages[pos][3] == "true")
         {
            img.style.width = filmstripSize + "px";
            img.style.height = "auto";
         }
         else
         {
            img.style.height = filmstripSize + "px";
            img.style.width = "auto";
         }
         img.style.borderWidth = "4px";
         img.style.borderStyle = "solid";
         img.style.borderColor = (i==3)?'rgb(255,198,0)':'white';
      }
      else
      {
         img.src="";
         img.style.width="0";
         img.style.height="0";
         img.style.borderStyle="none";
         img.style.borderWidth="0";
      }
   }
}

function AdvanceFilmstrip(img)
{
   var i = parseInt(img.id.split("_")[1]);
      
   if(i < 3) { PrevImage(3-i); } 
   else if(i > 3) { NextImage(i-3); }
}

var reqLVMetadata;
function updateMetadata(myImagesIndex)
{
      url = "asyncLVMetadata.php?idfile=" + myImages[myImagesIndex][0] + 
         "&itemid=" + myImages[myImagesIndex][1] + "&name=" + myImages[myImagesIndex][2] + "&lbx=" + myLbx;
      reqLVMetadata = getRequestObject();
      reqLVMetadata.onreadystatechange = reqLVMetadataTable;
      reqLVMetadata.open("POST", url, true);
      reqLVMetadata.send(null);
}


function reqLVMetadataTable()
{
   if (4 == reqLVMetadata.readyState)
   {
      if(Handle302(reqLVMetadata))
      {
         return;
      }
      if (200 == reqLVMetadata.status || null == reqLVMetadata.status)
      {
         var rsp = reqLVMetadata.responseText;
         document.getElementById("imageMetadata").innerHTML = rsp;
            
      }
      else if (399 < reqLVMetadata.status)
         alert('HTTP error ' + reqLVMetadata.status + ': ' + reqLVMetadata.statusText);
   }
}

function updateViewChkBx (id)
{
//    var req = loadJSONDocPOST('largeviewjson.php', 'task=getchkbox&id=' + id + '&lbx=' + myLbx);
//    req.addCallbacks(setChkBx, chkFail);
   jQuery.getJSON('largeviewjson.php?task=getchkbox&id=' + id + '&lbx=' + myLbx, 
     function(data) {setChkBx(data);});
}

function setChkBx (meta)
{
    if (meta.results.id == myImg + "")
    {
        document.getElementById('LVCheckBox').checked = meta.results.checked;
    }
}

function chkFail (err)
{
    alert('Failure Updating Checkbox!');
}

function updateLVButtons(img)
{
   var fullDownload = document.getElementById("downloadFull");
   if(fullDownload != null)
   {
      fullDownload.href = "javascript: DownloadForSales(" + img + ",'original')";
   }
   var compDownload = document.getElementById("downloadComp");
   if(compDownload != null)
   {
      compDownload.onclick = 
         function () {
            DownloadForSales(img, 'large');
            return false;
         }
   }
   var request = document.getElementById("request");
   if(request != null)
   {
      request.href = "javascript: ShowRequestPopup(" + img + ")";
   }
   var addToLbx = document.getElementById("addToLbx");
   if(addToLbx != null)
   {
      addToLbx.href = "javascript: ShowAddToLbxPopup(" + img + ")";
   }
   var orderPrint = document.getElementById("print");
   if(orderPrint != null)
   {
      orderPrint.onclick = 
         function () { 
            window.location.href='purchase.php?tab=orderPrint&id=' + img + '&container=' + containerId;  
            return false;
         }
   }
   var license = document.getElementById("license");
   if(license != null)
   {
      license.onclick = 
         function () {
            window.location.href='purchase.php?tab=download&id=' + img + '&container=' + containerId;
            return false;
         }
   }
}

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=/";
}

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);
}

var rowCount = "3";


var reqLBMgmtUrl = "asyncLBMgmt.php";

function reqLBMgmtDropdown()
{
   if (4 == reqLBMgmt.readyState)
   {
      if (200 == reqLBMgmt.status || null == reqLBMgmt.status)
      {
         var rsp = reqLBMgmt.responseText;
         var ok = 'Success: ';
         if (rsp.substring(0, ok.length) == ok)
         {  // Dont think we need to do anything with this since already selected(??)
            var newActive = rsp.substring(ok.length);
         }
         else
         {  // TODO: need to set selection back to what it was
            alert(rsp);
         }
      }
      else if (399 < reqLBMgmt.status)
         alert('HTTP error ' + reqLBMgmt.status + ': ' + reqLBMgmt.statusText);
   }
}

/**
*  Switch to a different lightbox.
*/
function salesLightboxChange()
{
   if (document.getElementById('selectLB').value == "A") 
   {
      //LB_open('pop_addnewlbjs.php','no',150,398,400,400,400,400,400,400,400);
      LB_open('pop_addnewsaleslb.php','yes',250,398,400,400,400,400,400,400,400);
   }

   if (document.getElementById('selectLB').value == "s") 
   {
      document.getElementById('selectLB').options[0].selected = true;
   }

   if (document.getElementById('selectLB').value != "s" && document.getElementById('selectLB').value != "A") 
   {
      query = "lbx=" + document.getElementById('selectLB').value + "&action=changeActive";
      if ( 0 > this.location.pathname.search(/userLightbox/) )
      {
	      reqLBMgmt = getRequestObject();
	      reqLBMgmt.onreadystatechange = reqLBMgmtDropdown;
	      reqLBMgmt.open("POST", reqLBMgmtUrl + "?" + query, true);
	      reqLBMgmt.send(null);
	   }
      else
         this.location.search = query;
      
   }
}

function AddToLightbox(selected)
{
      if ( -1 == document.getElementById('selectLB').selectedIndex )
      {
         alert("No lightbox selected.");
         return false;
      }
      
      if (document.getElementById('selectLB').value == "s" || document.getElementById('selectLB').value == "A")
         return false; 

/* TODO: Check on client for no boxes selected      
      if ( 'none' == selected ) 
      {
         alert("No images selected.");
         return false;         
      }
*/
      
      query = "toLbx=" + document.getElementById('selectLB').value + "&adds=" + selected + "&action=addToLightbox";
      if ( 0 > this.location.pathname.search(/userLightbox/) )
      {
	      reqLBMgmt = getRequestObject();
	      reqLBMgmt.onreadystatechange = reqLBMgmtAdd;
	      reqLBMgmt.open("POST", reqLBMgmtUrl + "?" + query, true);
	      reqLBMgmt.send(null);         
      }
      else
         this.location.search = query;
        
}   

function reqLBMgmtAdd()
{
   if (4 == reqLBMgmt.readyState)
   {
      if (200 == reqLBMgmt.status || null == reqLBMgmt.status)
      {
         var rsp = reqLBMgmt.responseText;
         var ok = 'Success: ';
         if (rsp.substring(0, ok.length) == ok)
         {  
            alert( "Images(s) added to " + document.getElementById('selectLB').options[document.getElementById('selectLB').selectedIndex].text );         
         }
         else
         {  
            alert(rsp);
         }
      }
      else if (399 < reqLBMgmt.status)
         alert('HTTP error ' + reqLBMgmt.status + ': ' + reqLBMgmt.statusText);
   }
}

function RemoveFromLightbox(selected)
{
      if ( -1 == document.getElementById('selectLB').selectedIndex )
      {
         alert("No lightbox selected.");
         return false;
      }
      
      if (document.getElementById('selectLB').value == "s" || document.getElementById('selectLB').value == "A")
         return false; 
      
/* TODO: Check on client for no boxes selected
      if ( 'none' == selected ) 
      {
         alert("No images selected.");
         return false;         
      }
*/
      
      query = "lbx=" + document.getElementById('selectLB').value + "&deletes=" + selected + "&action=deleteFromLightbox";
      if ( 0 > this.location.pathname.search(/userLightbox/) )
      {
         reqLBMgmt = getRequestObject();
         reqLBMgmt.onreadystatechange = reqLBMgmtRemove;
         reqLBMgmt.open("POST", reqLBMgmtUrl + "?" + query, true);
         reqLBMgmt.send(null);         
      }
      else
         this.location.search = query;
        
}   

function reqLBMgmtRemove()
{
   if (4 == reqLBMgmt.readyState)
   {
      if (200 == reqLBMgmt.status || null == reqLBMgmt.status)
      {
         var rsp = reqLBMgmt.responseText;
         var ok = 'Success: ';
         if (rsp.substring(0, ok.length) == ok)
         {  
            //will become apparent with page refresh
            //alert( "Images(s) added to " + document.getElementById('selectLB').options[document.getElementById('selectLB').selectedIndex].text );         
         }
         else
         {  
            alert(rsp);
         }
      }
      else if (399 < reqLBMgmt.status)
         alert('HTTP error ' + reqLBMgmt.status + ': ' + reqLBMgmt.statusText);
   }
}
function deleteActiveLB()
{
      if ( -1 == document.getElementById('selectLB').selectedIndex )
      {
         alert("No lightbox selected.");
         return false;
      }
      
      if (document.getElementById('selectLB').value == "s" || document.getElementById('selectLB').value == "A")
         return false; 
      
      if ( false == confirm( "Are you sure you want to delete the " + 
         document.getElementById('selectLB').options[document.getElementById('selectLB').selectedIndex].text + " lightbox?" ) )
         return false;

      query = "lbx=" + document.getElementById('selectLB').value + "&action=deleteLightbox";
      if ( 0 > this.location.pathname.search(/userLightbox/) )
      {
	      reqLBMgmt = getRequestObject();
	      reqLBMgmt.onreadystatechange = reqLBMgmtDelete;
	      reqLBMgmt.open("POST", reqLBMgmtUrl + "?" + query, true);
	      reqLBMgmt.send(null);         
      }
      else
         this.location.search = query;
        
}   

function reqLBMgmtDelete()
{
   if (4 == reqLBMgmt.readyState)
   {
      if(Handle302(reqLBMgmt))
      {
         return;
      }
      if (200 == reqLBMgmt.status || null == reqLBMgmt.status)
      {
         var rsp = reqLBMgmt.responseText;
         var ok = 'Success: ';
         if (rsp.substring(0, ok.length) == ok)
         {  
            alert( document.getElementById('selectLB').options[document.getElementById('selectLB').selectedIndex].text + 
               " has been successfully deleted." );         
            document.getElementById('selectLB').options[document.getElementById('selectLB').selectedIndex] = null;   
         }
         else
         {  
            alert(rsp);
         }
      }
      else if (399 < reqLBMgmt.status)
         alert('HTTP error ' + reqLBMgmt.status + ': ' + reqLBMgmt.statusText);
   }
}

function CompleteRequestOrder(orderId)
{
   var uri = 'purchase.php?tab=download&product=' + escape(orderId);
   window.location.href = uri;
}

function LicenseOrder(imageId, containerId)
{
   var uri = 'purchase.php?tab=download&id=' + escape(imageId) + '&container=' + escape(containerId);
   window.location.href = uri;
}

function DownloadForSales(ids, size, container, order)
{
   if(size == "large" || size == "medium") { size = "large_sales";}
   else if (size == "small") { size = "small_sales"; }

   var uri = '../pop_progress.php?progress_action=pop_downloadimg1.php&progress_message=Your+images+are+being+compressed+for+delivery.' 
             + '&position=sales&ids=' + ids + '&size=' + size + '&compress=zip';
   if(container != null)
   {
      uri += "&container=" + container;
   }
   if(order != null)
   {
      uri += "&order=" + order;
   }
   MM_openBrWindow(uri,'','scrollbars=yes,width=756,height=580,top=0,left=0');  
}

function GetSearchPageParameters(excludeSearchAction)
{
   if ( null == document.advSearch )
      return '';
   
   querystring = '';   
   for ( i=0; i < document.advSearch.elements.length; i++ )
   {
      if ( ( null != document.advSearch.elements[i].value ) && ( '-1' != document.advSearch.elements[i].value )
         &&  ( '-2' != document.advSearch.elements[i].value ) && ( '' != document.advSearch.elements[i].value )
         && ( 'all' != document.advSearch.elements[i].value ) )
      {
         // Bug 9266, 9277
         if ('searchAction' == document.advSearch.elements[i].name && excludeSearchAction)
            continue;
         if ('ck_' == document.advSearch.elements[i].name.substr(0,3))
         {
            if ( true != document.advSearch.elements[i].checked )
               continue;
         }
         if ('__' == document.advSearch.elements[i].name.substr(0, 2))
            continue;
         querystring += '&' + document.advSearch.elements[i].name + '=' + document.advSearch.elements[i].value;  
      }
   }
   
   return querystring;
}

function Handle302(request)
{
   if(request != null && request.status != null)
   {
       if (request.status == 302 || request.status == 12150)
       {
          redirect = request.getResponseHeader("Location");
          request.open("POST", redirect, true);
          request.send("");
          return true;
       }
   }
   return false;
}

function getRequestObject()
{
   if (window.XMLHttpRequest)
      return new XMLHttpRequest();
   else if (window.ActiveXObject)
      return new ActiveXObject("Microsoft.XMLHTTP");
}

function requestsError()
{
   //alert("Asynchronous Javascript failed; operation unsuccessful");
}

function simpleSearch()
{
   document.search.submit();
}

function enterSearch(e)
{
   var k;
   if (navigator.appName=="Netscape" || navigator.appName=="Mozilla") {k = e.which;}
   else {k = e.keyCode;}
   if (k==13) { simpleSearch(); }
}

function DisableEnterSubmit(e)
{
   if (navigator.appName=="Netscape" || navigator.appName=="Mozilla") {k = e.which;}
   else {k = e.keyCode;}
   if (k==13) { return false; }
   return true;
}

var searchStarted = false;

function StartSearch()
{
   if(!searchStarted)
   {
      searchStarted = true;
      return true;
   }
   else
   {
      return false;
   }
}


document.onmousedown = null;
document.onmouseup = null;
document.onmousemove = CaptureMouse;
dragged = null;

startCoords = {x:0,y:0};
mouseCoords = {x:0,y:0};

function CaptureMouse(e)
{
   e = e || window.event;
   mouseCoords = GetMouseCoords(e);
   if(dragged != null)
   {
      var top = -parseInt(dragged.style.top.split('px')[0]);
      var left = -parseInt(dragged.style.left.split('px')[0]);
      var diffX = mouseCoords.x - startCoords.x;
      var diffY = mouseCoords.y - startCoords.y;
      top -= diffY;
      left -= diffX;
      if (top < 0) { top = 0; }
      if (top > imgMaxTop) { top = imgMaxTop; }
      if (left < 0) { left = 0; }
      if (left > imgMaxLeft) { left = imgMaxLeft; }
      dragged.style.top = '-' + top + 'px';
      dragged.style.left = '-' + left + 'px';
      startCoords = mouseCoords;
   }
}

function GetMouseCoords(e)
{
   if(e.pageX || e.pageY)
   {
      return {x:e.pageX, y:e.pageY};
   }
   mouseX = e.clientX + document.body.scrollLeft - document.body.clientLeft;
   mouseY = e.clientY + document.body.scrollTop  - document.body.clientTop ;
   return {x:mouseX, y:mouseY};
}

function CheckHomeLink()
{
   if(mouseCoords.x >= 35 && mouseCoords.x <= 400 && mouseCoords.y >= 25 && mouseCoords.y <= 95)
   {
      window.location.href = "home.php";
   }
}
