var currentCategory = -1;
var currentJob = "_NO_JOB";
var jobIncr=1;
var waitingbuttonid=null;
var waitabletransitions;

function ResetButtonWait(button)
  {
    if(button)
	{
      button.style.display = '';
  	  button.removeAttribute('disabled');
	  button.disabled=false;
	if($("wait" + button.id))
	  $("wait" + button.id).remove();
	  }

  }
  
function SetButtonWait(button)
  {
     var btn = document.createElement('input');

	btn.type= "button";
	btn.id="wait" + button.id;
    btn.disabled = true;
    btn.value = "Please Wait..";
    btn.className=button.className;
    button.parentNode.insertBefore(btn, button);
    button.style.display = 'none'; 
	waitingbuttonid=button.id;
    setCookie('waitingbuttonid', waitingbuttonid);

  }

function SetButtonWaitevent(e)
  {
    var button=Event.element(e);
    var btn = document.createElement('input');

	btn.type= "button";
    btn.disabled = true;
    btn.value = "Please Wait..";
    btn.className=button.className;
        button.parentNode.insertBefore(btn, button);
        button.style.display = 'none';	
  }

Event.observe(window, "load", function() {

  waitabletransitions = document.getElementsByClassName('waitclick');
  for(var i=0; i<waitabletransitions.length; i++)
    {
      Event.observe(waitabletransitions[i], 'click', SetButtonWaitevent.bindAsEventListener(waitabletransitions[i]));
    }

    waitingbuttonid=getCookie('waitingbuttonid', waitingbuttonid);
  	if(waitingbuttonid!=null){  
      ResetButtonWait($(waitingbuttonid));
	  waitingbuttonid=null;	}
  var sourcedrives = document.getElementsByClassName('sourcedrive'), highnumb=0;
  for(var i=0; i<sourcedrives.length; i++)
    {
	  var snumb = Number(sourcedrives[i].id.replace(/\D+/g, ''));
	  if(snumb>highnumb)
	    highnumb=snumb;

	}



 var cookieValue = decodeDriveKey(getCookie("currentJob"));
 
 var expandedCategory =  getCookie("category");

  var delboxes = document.getElementsByClassName('togdeleted');
  for(var i=0; i<delboxes.length; i++)
    {
      delboxes[i].checked=false;
	}
  if(highnumb>=jobIncr)
    jobIncr=Number(highnumb)+1;
  if(expandedCategory!=null)
    toggleProducts(expandedCategory);
  else if (currentCategory == -1)
    toggleProducts(2);

  if(currentJob=="_NO_JOB" && highnumb>0)
    {
	toggleJobs("SourceDrive" + highnumb)
	}


});
function collapseOpenJob() 

{
  if (currentJob != "_NO_JOB")
  {
    $("job" + currentJob).hide();
    $("arrowON" + currentJob).hide();
    $("arrowOFF" + currentJob).show();
  }
}
function toggleJobs(job_id)
{
  if (currentJob != "_NO_JOB"  && currentJob != job_id) {
    collapseOpenJob();
  }
  if (currentJob != job_id) {
    currentJob = job_id;
    $("job" + job_id).toggle();
    $("arrowON" + currentJob).toggle();
    $("arrowOFF" + currentJob).toggle();
    if (currentJob == job_id) {
    }
  }
 }

function toggleProducts(catid)
{
  if($("prod" + catid)){
  if (currentCategory != -1 && currentCategory != catid) {
    $("prod" + currentCategory).hide();
    $("arrowON" + currentCategory).hide();
    $("arrowOFF" + currentCategory).show();
  }
  currentCategory = catid;

  $("prod" + catid).toggle();
  $("arrowON" + currentCategory).toggle();
  $("arrowOFF" + currentCategory).toggle();
    setCookie('category', catid);
}
  }
function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}
function decodeDriveKey(key) {
  if (key) {
    var key = key.replace("_plus_", "+");
    key = key.replace("_amp_", "&");
    key = key.replace("_pound_", "#");
    key = key.replace("_perc_", "%");
  }
  return key;
}

function encodeDriveKey(key) {

  return key;  
}

function postToAddCart(prodid, tries)
{
    if (tries == undefined) {
      tries = 0;
    }

    waitingbuttonid='atcb' + prodid;

    SetButtonWait($(waitingbuttonid));	

    var jn = "";
    var driveKey = currentJob;
	var includeDel = "false";
	if(deletedArray[prodid]=="true")
	  includeDel="true";
    new Ajax.Request("/cart/add.php?action=add-cart:" + prodid + "&drivekey=" + encodeDriveKey(driveKey) + "&qty=1&del=" + includeDel,
    {
      method: "POST",
      on202: function(transport) {
	  
        window.location.reload();	
      },
      on200: function(transport) {
	showConfigForm(transport.responseText);

	},
      on412: function(transport) {
        alert("You have selected an invalid storage device for the EDP requested.  Please select a storage device and try again.");
      },      
	  on422: function(transport) {
        alert("The EDP selected is identical to one already configured for this storage device.  Please select a different storage device or add a different EDP.");
      },   
	  on499: function(transport) {
	    showConfigForm(transport.responseText);
      }, 	  
      onFailure: function(transport) {
       //retry if IE sporradically fails. 
       tries = tries + 1;
       if (transport.status > 12000 && tries < 4) {
	 setTimeout("postToAddCart('" + prodid + "'," + tries + ")", 100)
       }
       else {
         alert("An unexpected error has occurred. Please contact technical support." + transport.status + "\n\n" + transport.responseText);
        window.location.reload();

		 }
       //alert(transport.status);
      }

    });

}

function hideJobkeyForm() {
  $('drivekey_display').show();
  $('drivekey_form').hide();
}
function Cancel() {
  hideJobkeyForm();
}
function showForm() {
  $('drivekey_display').hide();
  $('drivekey_form').show();
}

function removeJob(key) {
  $('dynamic_joblist').update('');
  $('drivekey_form').show();
  currentJob = "_NO_JOB";

}

function AddJob()
{

    collapseOpenJob();
    $('empty_msg').hide();
    currentJob = "SourceDrive" + jobIncr++;


	new Insertion.Bottom('dynamic_joblist', "<div class=\"category\"><table class=\"productCat\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"><tr><td width=\"25\" align=\"center\"><a style='display:None' id=\"arrowOFF" + currentJob + "\" href=\"#\"><img onclick=\"toggleJobs('" + currentJob + "')\" src=\"/images/arrowOFF.png\" border=\"0\" width=\"22\" height=\"21\" /></a><a id=\"arrowON" + currentJob + "\"  href=\"#\"><img onclick=\"toggleJobs('" + currentJob + "')\" src=\"/images/arrowON.png\" border=\"0\" width=\"22\" height=\"20\" /></a></td><td width=\"37\"><img src=\"../../images/icons/sourcedrive.png\" width=\"26\" height=\"32\"/></td><td><a href=\"#\" onclick=\"toggleJobs('" + currentJob + "')\"><span class='edp_text2'>" + currentJob + "</span></a></td></tr></table></div><div class='products' style='overflow:auto; height:200px' id='job" + currentJob + "'><p class=\"edp_text\">This Source Drive is empty. Add EDP items from the left to continue. </p><hr style=\"border-style: none none solid; border-color: -moz-use-text-color; border-width: thin; width: 100%;\"/></div>");
	
	
    $('drivekey_form').hide();  
  

}

function postConfigForm(mode, tries)
{
  if(js!=null){
 if(typeof(js.PreSubmit) == 'function')
  if( !js.PreSubmit()) {
  return false;
 }
 }
 

if ($("tomato_js") != null){
  var tomtry = eval($("tomato_js").innerHTML);

    if(!tomtry)return false;
  }
    if (tries == undefined) {
      tries = 0;
    }
    new Ajax.Request("/cart/configure.php",
    {
      method: "POST",
      postBody: $('configure_form').serialize() + "&nav_button=" + mode,
      on412: function(transport) {
	  alert('There was an error with your request.  Are all the required fields filled in?');
	  
      },  
	  on422: function(transport) {
        alert("The EDP selected is identical to one already configured for this storage device.  Please select a different storage device, add a different EDP, or reconfigure the currently selected EDP.");
      },
      onSuccess: function(transport) {
	if (mode == "Back" || mode == "Next") {

          updateConfigForm(transport.responseText);
	}
	else if (mode == "Finished")
	{
	      Windows.getWindow('product_config_window').close();   

          window.location.reload();
	}
      },
      onFailure: function(transport) {
       //retry if IE sporradically fails. 
       tries = tries + 1;
       if (transport.status > 12000 && tries < 4) {
	 setTimeout("postConfigForm('" + mode  + "'," + tries + ")", 100)
       }
       else {
         alert("An unexpected error has occurred. Please contact technical support." + transport.status + "\n\n" + transport.responseText);
       }
      }
      

    });
}

function configureExistingEdp(lid) 
{
;
}

function removeFromCart(lid, physical)
{

    SetButtonWait($('rfcb' + lid));	



    new Ajax.Request("/cart/remove.php?lid=" + lid + "&physical=" + physical,
    {
      method: "GET",
      onSuccess: function(transport) {
        window.location.reload(true);
      },
      onFailure: function(transport) {
       alert("An unexpected error has occurred. Whatever you did, don't do it again");
      }
    });

}

function configFormFinished() {

  var ret=postConfigForm("Finished");

	if(waitingbuttonid!=null){  
      ResetButtonWait($(waitingbuttonid));
	  waitingbuttonid=null;	}
	if(ret==undefined)
    ret= true;

  return ret;
}
function configFormBack() {
  postConfigForm("Back"); 
}

function configFormNext() {
  extrabody = "&nav_button=Next";
  postConfigForm("Next"); 
}

function configFormCancel() {
//  extrabody = "&nav_button=Cancel";

	if(waitingbuttonid!=null){  
      ResetButtonWait($(waitingbuttonid));
	  waitingbuttonid=null;	}
  Windows.getWindow('product_config_window').close();   

}

var formJS = Class.create();
var js;
function updateConfigForm(formData)
{
  $('config_form').update(formData);
}

function execJS()
{

  js=null;
  if ($("form_js") != null) {
    eval($("form_js").innerHTML); 
    js = new formJS();
  }

}

var dialog;
function showConfigForm(formData) {

if (!Windows.getWindow('product_config_window')){
winwidth=750;
winheight=450;


var re = new RegExp('BFWinDim:([0-9]+),([0-9]+)');
  var m = re.exec(formData);
  if (m == null) {
    ;
  } else {
winwidth=m[1];
winheight=m[2];
    }



dialog = Dialog.info("<div id='config_form'>" + formData + "</div>",
    {//top: 10,
      id: 'product_config_window',
      width:winwidth,
      height:winheight,
      className: "alphacube",
      onShow: execJS,
      onOk: function() {postToAddCart();}
     })};

}

function showFlash(file, audio) {

if (!Windows.getWindow('flash_window')){
winwidth=644;
winheight=490;

code="<div style=\"float: right\"><input class=\"btn4\" type=\"button\" onclick=\"closeFlash()\" value=\"Close Window\"/></div><OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\" WIDTH=\"615\" HEIGHT=\"461\" id=\""+file+"\" ALIGN=\"\"><PARAM NAME=movie VALUE=\""+file+".swf\"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=white> <EMBED src=\""+file+".swf\" quality=high bgcolor=\"white\" WIDTH=\"615\" HEIGHT=\"461\" NAME=\""+file+"\" ALIGN=\"\" TYPE=\"application/x-shockwave-flash\" PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\"></EMBED> </OBJECT> ";

if(!audio)
  code=code+"<span style=\"opacity:.5\;float: left\" class=\"Main_Text\"><i>Guidance: This video has no sound</i></span>";

dialog = Dialog.info("<div id='flash_box'>" + code + "</div>",
    {//top: 10,
      id: 'flash_window',
      width:winwidth,
      height:winheight,
      className: "alphacube",
      onShow: execJS,
      onOk: function() {postToAddCart();}
     })};

}

function closeFlash() {
Windows.getWindow('flash_window').close();
}

var deletedArray = [];
function toggleDeletedFlag(prodid)
{
  if(deletedArray[prodid]==undefined)
    deletedArray[prodid]="true";
  else deletedArray.splice(prodid, 1);
}
function addToCartHandler(prodid)
{


  if (currentJob != "_NO_JOB")
  {
  setCookie('currentJob', encodeDriveKey(currentJob));
   postToAddCart(prodid);
  }
  else {
    AddJob();
  setCookie('currentJob', encodeDriveKey(currentJob));
   postToAddCart(prodid);
  }

}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*thaxton functions below*/
var SUNBLOCK = (function () {
    var VALIDATE_DRIVE_KEY_URL = 'validateDriveKey.php',
        VALIDATE_COUPON_CODE_URL = 'validateCouponCode.php',
        VALID_RESPONSE = /\{true\}/,
        INVALID_FILENAME = /[\*\"\\/:<>\?'()\|\.]/;
    function initBillingForm (error_message) {
        var check_box = $('terms'),
            billing_form = $('billing_form'),
            error_is_displayed = false;
        function validateForm (event) {
		        SetButtonWait($('submitbutton'));
            if (!check_box.checked) {
                showError();
    ResetButtonWait($('submitbutton'));
	Event.stop(event);
				return;
            }		  
        }
        function showError () {
            if (!error_is_displayed) {
				error_node = document.getElementById('the_form_error');
				error_node.innerHTML = 'Accept the Terms and Conditions to continue.';
            }
        }
        Event.observe(billing_form, 'submit', validateForm);
    }
    function initFinalizeForm () {
        var drives = document.getElementsByClassName('drive_detail'),

            finalize_form=$('finalize_form'),
            coupon_field = $('coupon'),
            validated_coupon_value = null,
            coupon_error = $('coupon_error'),
            current_cc_query = null,
            submit_in_progress = false,
            submit_on_complete = false;
			

			
        for (var i = 0, limmit = drives.length; i < limmit; i++) {
            drives[i].validate = function () {
                if (this.validateDriveKey() && this.validateFilename()) {
                    return true;
                } else {
                    return false;
                }
            };
            drives[i].validateDriveKey = function () {

                var drive_key,
                    pattern = new RegExp('^[0123456789abcdefghijk~mn\+pqrstuvwxyz#&%@ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$');
                try {
                    drive_key = this.drive_key_inputs[0].value + this.drive_key_inputs[1].value + this.drive_key_inputs[2].value;
			    					} catch (e) {
                    this.showDriveKeyError();
                    return false;
                }
				if(drive_key.length<12)
                  {
 				    return false;
				  }
                if (pattern.test(drive_key)) {

                    if (drive_key == this.validated_drive_key) {
                        this.hideDriveKeyError();
                        return true;
                    } else {
                        if (submit_in_progress) {
                            submit_on_complete = true;
                        }
                        queryDriveKey(this);
                        return false;
                    }
                } else {
                    this.showDriveKeyError();
                    return false;
                }
                function queryDriveKey (that) {
                    if (that.current_dk_query == drive_key) {
                        return;
                    } else {
                        that.current_dk_query = drive_key;
                    }
                    new Ajax.Request(VALIDATE_DRIVE_KEY_URL, {
                        method : 'get',
                        parameters : {drive_key:drive_key},
                        onSuccess : function (transport) {
                            if (transport.responseText.match(VALID_RESPONSE)) {

                                that.validated_drive_key = drive_key;
                                that.hideDriveKeyError();
                                if (submit_on_complete) {
                                    finalize_form.submit();
                                    submit_on_complete = false;
                                }
                            } else {
                                that.showDriveKeyError();
                            }
                        },
                        onFailure : function (transport) {
                            that.showDriveKeyError();
                        },
                        onComplete : function (transport) {
                            that.current_dk_query = null;
                        }
                    });
                }
            };
            drives[i].current_dk_query = null;
            drives[i].drive_key_error = drives[i].getElementsByClassName('drive_key_error')[0];
            drives[i].showDriveKeyError = function () {
                this.drive_key_error.removeClassName('hide');
            };
            drives[i].hideDriveKeyError = function () {
                this.drive_key_error.addClassName('hide');
            };
            drives[i].validated_drive_key = null;
            drives[i].drive_key_inputs = drives[i].getElementsByClassName('drive_key');
            drives[i].validateDriveKey();
            drives[i].validateFilename = function () {
                if (!INVALID_FILENAME.test(this.filename_input.value)) {
                    this.hideFilenameError();
                    return true;
                } else {
                    this.showFilenameError();
                    return false;
                }
            };
            drives[i].filename_error = drives[i].getElementsByClassName('filename_error')[0];
            drives[i].showFilenameError = function () {
                this.filename_error.removeClassName('hide');
            };
            drives[i].hideFilenameError = function () {
                this.filename_error.addClassName('hide');
            };
            drives[i].validated_filename = null;
            drives[i].filename_input = drives[i].getElementsByClassName('filename')[0];
            drives[i].validateFilename();
            Event.observe(drives[i].filename_input, 'blur', drives[i].validateFilename.bindAsEventListener(drives[i]));
            Event.observe(drives[i].filename_input, 'keyup', drives[i].validateFilename.bindAsEventListener(drives[i]));
            Event.observe(drives[i].drive_key_inputs[0], 'blur', drives[i].validateDriveKey.bindAsEventListener(drives[i]));
            Event.observe(drives[i].drive_key_inputs[0], 'keyup', drives[i].validateDriveKey.bindAsEventListener(drives[i]));
            Event.observe(drives[i].drive_key_inputs[1], 'blur', drives[i].validateDriveKey.bindAsEventListener(drives[i]));
            Event.observe(drives[i].drive_key_inputs[1], 'keyup', drives[i].validateDriveKey.bindAsEventListener(drives[i]));
            Event.observe(drives[i].drive_key_inputs[2], 'blur', drives[i].validateDriveKey.bindAsEventListener(drives[i]));
            Event.observe(drives[i].drive_key_inputs[2], 'keyup', drives[i].validateDriveKey.bindAsEventListener(drives[i]));
        }
        function validateForm (event) {
    SetButtonWait($('submitbutton'));	

		submit_in_progress = true;

            for (var i = 0, limmit = drives.length; i < limmit; i++) {
                if (!drives[i].validate()) {
    ResetButtonWait($('submitbutton'));	

				Event.stop(event);
					error_node = document.getElementById('the_form_error');
					error_node.innerHTML = 'Please fill in all required fields.';

                    break;
                }}
			if (!validateCoupon()) {
                Event.stop(event);
                submit_in_progress = false;
                ResetButtonWait($('submitbutton'));	

            }            
            submit_in_progress = false;
        }
        function validateCoupon () {
            if (coupon_field.value == '' || coupon_field.value == validated_coupon_value) {
                hideCouponError();
                return true;
            } else {

                queryCoupon();
                return false;
            }
            function queryCoupon () {
                var coupon_code = coupon_field.value;
                if (current_cc_query == coupon_code) {
                    return;
                } else {
                    current_cc_query = coupon_code;
                }
                new Ajax.Request(VALIDATE_COUPON_CODE_URL, {
                    method : 'get',
                    parameters : {coupon_code:coupon_code},
                    onSuccess : function (transport) {
                        if (transport.responseText.match(VALID_RESPONSE)) {
                            validated_coupon_value = coupon_code;
                            hideCouponError();
                            if (submit_on_complete) {
                                finalize_form.submit();
                                submit_on_complete = false;
                            }
                        } else {
                            showCouponError();
                        }
                    },
                    onFailure : function (transport) {
                        showCouponError();
                    },
                    onComplete : function (transport) {
                        current_cc_query = null;
                    }
                });
            }
        }
        function showCouponError () {
            coupon_error.removeClassName('hide');
        }
        function hideCouponError () {
            coupon_error.addClassName('hide');
        }
        validateCoupon();
        Event.observe(finalize_form, 'submit', validateForm);
    }
    function initAddressOption () {
	    billform = $('the_form');
        checkbox = $$('input[name="diffinfo"]')[0];
		hidethese = billform.getElementsByClassName('diffhide');
			if($('forcediff'))
			  toggleInputs();
		
        function toggleInputs () {
        //inputs = $$('input[name="address2"]','input[name="fullname"]', 'input[name="address1"]', 'input[name="city"]', 'select[name="state"]', 'select[name="country"]','input[name="zip"]', 'input[name="state"]');
inputs = $$('input[name="address2"]','input[name="fullname"]', 'input[name="address1"]', 'input[name="city"]', 'select[name="state"]', 'input[name="zip"]', 'input[name="state"]', 'input[name="country"]');
		for (var i = 0, limmit = inputs.length; i < limmit; i++) {
                if (inputs[i].disabled) {
                    inputs[i].disabled = '';
                } else {
                    inputs[i].disabled = 'disabled';
					inputs[i].value='';
					if(elem = $(inputs[i].id + '_error'))
					  elem.addClassName('hide');
					$('grp1_error').addClassName('hide');  
                }
            }
            for (var i = 0, limmit = hidethese.length; i < limmit; i++) {
                if (hidethese[i].hasClassName('hide')) {
                    hidethese[i].removeClassName('hide');
                } else {
                    hidethese[i].addClassName('hide');
                }
            }			
        }

        Event.observe(checkbox, 'click', toggleInputs);

    }
    return {
        billingForm : function (input) {initBillingForm(input);},
        finalizeForm : function () {initFinalizeForm();},
        addressOption : function () {initAddressOption();}
    };
})();

