﻿var UploadedFileName = ''; // when file is uploaded in the iframe, that script changes this variable to the guid based filename of the upload.aspx

function URLEncode(plaintext)
{
    var SAFECHARS = "0123456789" +					// Numeric
			        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
			        "abcdefghijklmnopqrstuvwxyz" +
			        "-_.!~*'()";					// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
    var encoded = '';
    for (var i = 0; i < plaintext.length; i++ ) {
        var ch = plaintext.charAt(i);
        if (ch == ' ') {
            encoded += '+';				// x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
	        if (charCode > 255) {
			    
		        encoded += '+';
	        } else {
		        encoded += '%';
		        encoded += HEX.charAt((charCode >> 4) & 0xF);
		        encoded += HEX.charAt(charCode & 0xF);
	        }
        }
    } // for
    
    return encoded;
        
}

var designer =
{    
    progress : { front : 'Front of the Product', back : 'Back of the Product', approve : 'Approval stage' },
    
    where : null, // is the progress stage of the current designer
    submitted:false,

    Update : function () // fire the function to update the preview images
    {
        frontFieldChanged();
        backFieldChanged();
    },
    ShowBack : function()
    {
        this.Update();
        this.where = this.progress.back;
        
        
        Hide('frontPreviewImage');
        Hide('backBtn');
        Hide('productTopFrontMessage');
        Hide('productTopFrontBelowImage');
        Hide('frontTitleDiv');
        Hide('productBottomFrontFields');
        
        Show('productTopBackPreviewImage');
        Show('productBottomBackFields');
        Show('productTopBackMessage');
        Show('productTopBackBelowImage');
        Show('frontBtn');
        Show('backPreviewImage');
        if (document.getElementById('backPreviewImage') != null) {
            document.getElementById('backPreviewImage').style.position = "";
        }          
        Show('backTitleDiv');
        Show('productBottomBackContinueButton');
        Show('productBottomXML');
        ShowPopUps();
    
    },
    ShowFront : function()
    {
        this.Update();
        this.where = this.progress.front;
        
        Hide('productApproveTop');
        Hide('productApprove');
        Hide('backPreviewImage');
        Hide('editBtn');
        Hide('frontBtn');
        Hide('productBottomBackFields');
        Hide('productTopBackPreviewImage');
        Hide('backTitleDiv');
        
        Show('frontTitleDiv');
        Show('productTopFrontPreviewImage');
        Show('frontPreviewImage');
        if (document.getElementById('frontPreviewImage') != null) {
            document.getElementById('frontPreviewImage').style.position = "";
        }        
        Show('productTopFrontMessage');
        Show('productTopFrontBelowImage');
        Show('updateBtn');
        Show('productBottom');
        Show('backBtn');
        Show('productBottomFrontFields');
        if (backFields.length == 0) 
        { 
            Show('productBottomBackContinueButton');
        } else {
            Hide('productBottomBackContinueButton');
        }
        Show('productBottomXML');
        ShowPopUps();

    
    },
    
    Edit : function() // Edit product button was pressed
    {
        this.ShowFront();
    
    },
    
    Continue : function() // Show the approval screen
    {
        this.Update();
        this.where = this.progress.approve;
        
        //Show the approve screen

        Hide('productTopFrontMessage');
        Hide('productTopFrontBelowImage');
        Hide('productTopBackMessage');
        Hide('productTopBackBelowImage');
        Hide('productBottomBackContinueButton');
        Hide('productBottomXML');
        Hide('backTitleDiv');
        Hide('frontTitleDiv');
 
        Hide('updateBtn');
        Hide('backBtn');
        Hide('frontBtn');
        
        Hide('productBottom');        
        
        Show('frontPreviewImage');
        if (document.getElementById('frontPreviewImage') != null) {
            document.getElementById('frontPreviewImage').style.position = "relative";
            document.getElementById('frontPreviewImage').style.left = -220;
        }
        Show('backPreviewImage');
        if (document.getElementById('backPreviewImage') != null) {
            document.getElementById('backPreviewImage').style.position = "relative";
            document.getElementById('backPreviewImage').style.left = -220;
        }        
        //document.getElementById('backPreviewImage').style.left = 0;
        Show('editBtn');
        Show('productApprove');
        Show('productApproveTop');
        Show('productTopBackPreviewImage');

    },
    
    Approve : function() // submit the product to the cart event
    {

        if (E('initials').value.length < 1)
        {
            alert('Please initial your approval.');
            return;
        }
        
        if (E('ApprovalReferenceReq') != null) {
            if (E('ApprovalReference').value.length < 1)
            {
                alert('Please provide an Approval Reference.');
                return;
            }        
        }
        
        if (E('cbCustomerAgreementRequired') != null) {
            if (E('cbCustomerAgreementRequired').checked == false)
            {
                alert('You must agree to the terms.');
                return;            
            }
        }
        
        if (this.submitted) // our hack for submitonce() of the storefront
        {
            window.location = "shoppingcart.aspx"; //hopefully this url does not change :(
            return;
        }
        else
        {
            this.submitted = true;
        }
        // read frontFields and backFields array for elementIds, and then submit their values
        // take the action and append our custom values to it
        var customPost = "&notes=" + encodeURIComponent(E('notes').value);
        customPost = customPost + "&initials=" + encodeURIComponent(E('initials').value);
//        alert(E('ApprovalReferenceReq').value);
//        alert(E('ApprovalReference').value);
        if (E('ApprovalReference') != null) {
            customPost = customPost + "&ApprovalReference=" + encodeURIComponent(E('ApprovalReference').value);
        }
        
        
        for(i=0;i<frontFields.length;i++) 
        { 
            customPost=customPost+'&front' + frontFields[i]+'=' + encodeURIComponent(E(frontFields[i]).value); 
        }
        
        for(i=0;i<backFields.length;i++) 
        { 
//            if (E(backFields[i]) != null)
                customPost=customPost+ '&back' + backFields[i]+'=' + encodeURIComponent(E(backFields[i]).value); 
        }
        
        customPost = customPost + '&ShoppingCartRecID=' + ShoppingCartRecID;
            
        
        // console.debug("new post url " + customPost);

        document.forms[AddToCartFormName].action = document.forms[AddToCartFormName].action + customPost;

       // there is a bug in the strorefront's form validation, and since this package assumes that there is only a drop down, we are bypassing storefront's product validation 
       // if (validateForm(document.forms[AddToCartFormName]) && AddToCartForm_21_30_Validator(document.forms[AddToCartFormName]))
       // {
       
            
      
            document.forms[AddToCartFormName].submit(); // submitting the product with the customPost string as if the user pressed the 'invisible' add to cart button

       // }
        

    },
    
    SetUploadedFileName : function(fileName, formFieldId)
    {        
        E('UploadedImage' + String(formFieldId)).src = 'upload/' + fileName;
        E(formFieldId).value = fileName;
        //console.debug(E('UploadedImage').src);
        Show('UploadedImageDiv' + String(formFieldId));
        //E(UploadedFormFieldId).value = fileName;
        E('UploadedImageiFrame' + String(formFieldId)).height = '55px';
        this.Update();
    },
    
    GetUploadedFileName : function()
    {
        if (UploadedFileName.Length() > 1)
            return UploadedFileName;
        else
            return false;
    
    },
    DeleteUploadedImage : function(formFieldId) // the delete uploaded image is clicked
    {
        Hide('UploadedImageDiv' + String(formFieldId));
        E('UploadedImageiFrame' + String(formFieldId)).height = '55px';
        E('UploadedImage' + String(formFieldId)).src = '';
        E(formFieldId).value = '';
        this.Update();
    },
    
    ChangedLogo : function(formFieldId, TemplateValue)  //either an icon was clicked or the radion button was clicked
    {
        var formName = 'formName' + formFieldId;
        var inputName = 'inputName' + formFieldId;
        

//            console.debug("formName: " + formName + " inpputName: " + inputName);

        
        // just in case, setting the radio button to be checked, because the function could have been invoked by clicking on the image        
    	for (i=0;i<document.forms[formName].elements[inputName].length;i++)
    	{
	        if (document.forms[formName].elements[inputName][i].value == TemplateValue)
	        {
	            document.forms[formName].elements[inputName][i].click();
	            break;
	        }
        }
        // now, no matter from where the function was invoked (either from button or image click
        // update the preview and simulate the backFieldChanged or frontFieldChanged based on the designer's where property
        // actually, the workaround instead of reimplementing the FieldChanged javascript functions, is to create a hidden textbox with the xml extension file and populate it with the data
        E(formFieldId).value = TemplateValue; //insert the value of the current icon TemplateValue into the hidden textbox
        this.Update();
        
        if (document.getElementById('PopUpDiv_' + formFieldId) != null) {
            //hide the popup for this selection
            document.getElementById('PopUpDiv_' + formFieldId).style.display = "none";
        }
        
        /*if (this.where == this.progress.front) 
        {
            frontFieldChanged();
        }else
        {
            backFieldChanged();
        }*/
    
        
    },

    DropDownChangedLogo : function(formFieldId)  //either an icon was clicked or the radion button was clicked
    {
        var formName = 'formName' + formFieldId;
        var inputName = 'sel' + formFieldId;
        var imgName = 'imglogo' + formFieldId;
        var sellist = document.forms[formName].elements[inputName];
        

//            console.debug("formName: " + formName + " inpputName: " + inputName);

        
        // just in case, setting the radio button to be checked, because the function could have been invoked by clicking on the image
        //String(fromSPYID.options[fromSPYID.selectedIndex].text
    	//for (i=0;i<document.forms[formName].elements[inputName].options.length;i++)
    	//{
	        //if (document.forms[formName].elements[inputName].options[i].selected)
	        //{
	            //document.forms[formName].elements[imgName].src="images/logos/" + sellist.options[sellist.selectedIndex].value;
	            //break;
	        //}
        //}
        // now, no matter from where the function was invoked (either from button or image click
        // update the preview and simulate the backFieldChanged or frontFieldChanged based on the designer's where property
        // actually, the workaround instead of reimplementing the FieldChanged javascript functions, is to create a hidden textbox with the xml extension file and populate it with the data
        E(formFieldId).value = sellist.options[sellist.selectedIndex].value; //insert the value of the current icon TemplateValue into the hidden textbox
        this.Update();
        //this code doesn't work in firefox but at least the preview was updated
        document.getElementById(imgName).src="images/logos/" + sellist.options[sellist.selectedIndex].value;
        //confirm(document.getElementById(imgName));
        
        /*if (this.where == this.progress.front) 
        {
            frontFieldChanged();
        }else
        {
            backFieldChanged();
        }*/
    
        
    },
    
    DropDownListChanged : function(ele)
    {
        
    },
    
    PopUpSelection : function(divid)
    {
        var bPos = elementPosition(document.getElementById('frontPreviewImage'));
        //confirm(bPos.x);
        if (document.getElementById(divid).style.display == "none") {
            document.getElementById(divid).style.display = "";
            document.getElementById(divid).style.left = bPos.x;
            document.getElementById(divid).style.top = bPos.y;
        } else {
            document.getElementById(divid).style.display = "none";
        }
    },
    
    ClosePopUpSelection : function(divid)
    {
        document.getElementById(divid).style.display = "none";
    }
}

function elementPosition(elem) {
    var x = 0;
    var y = 0;
			
    while (elem.offsetParent) {	
	    x += elem.offsetLeft + (elem.clientLeft || 0);
	    y += elem.offsetTop + (elem.clientTop || 0);
	    elem = elem.offsetParent;
    }
    return {x: x, y: y};
}

function ShowPopUps() {
    var bPos = elementPosition(document.getElementById('frontPreviewImage'))
    i=0;
    while (i<99) {
        if (document.getElementById('PopUpDiv_' + i) != null) {
            //only do this the first time so we do not drive people crazy
            if (document.getElementById('PopUpDiv_' + i).style.display == "block") {        
                document.getElementById('PopUpDiv_' + i).style.display = "";
                document.getElementById('PopUpDiv_' + i).style.left = bPos.x;
                document.getElementById('PopUpDiv_' + i).style.top = bPos.y;        
            }
        }
        i++;
    }
}

    

function E(id) // just a shortcut, like prototypes $()
{
   // try
   // {
        return document.getElementById(id);
    //}catch(ex){}
}

function Hide(id)
{
   // try
    //{
    
	var element = document.getElementById(id);
	if (element != null)
	{
	
        if (element.className)
        {
            if (element.className == 'displayBlock')
                element.className = 'displayNoneBlock';
            else if (element.className == 'displayInline')
                element.className = 'displayNoneInline';
        }

    }
    
    //console.debug("Hide " + id);
   // }catch(ex) {}

}
function Show(id)
{
   // try
   // {
    
	var element = document.getElementById(id);
	if (element != null)
	{
        if (element.className)
        {
            if (element.className == 'displayNoneBlock')
                element.className = 'displayBlock';
            else if (element.className == 'displayNoneInline')
                element.className = 'displayInline';
            
        
        }
        
    }
    //console.debug("Show " + id);
   // }catch(ex){}
}

window.onload= OnLoad;

function OnLoad()
{
    designer.Update();
}


function checkEnter(e){ //e is event object passed from function invocation
    var characterCode; //literal character code will be stored in this variable

    if(e && e.which){ //if which property of event object is supported (NN4)
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else{
        e = event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
        //document.forms[0].submit() //submit the form
        //return false;
        designer.Approve();
    }
    else{
        return true;
    }

}
