/*
 * Copyright (c) 2001-2008 Bridge Entertainment, Inc. (dba E-Poll)
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Bridge Entertainment, Inc. ("Confidential Information").
 */

/* ajax call to refresh the minicart */
function refreshMiniCart() {
    // alert("MiniCart will now be refreshed.");
    new Ajax.Request("/store/Minicart.do?time=" + new Date().getTime(), {
        method: 'get',
        onSuccess: function(transport) {
            $('columnimage').innerHTML = transport.responseText;
        },
        onFailure: function() {
            alert('There was an error refreshing the cart.');
        }
    });
}

/* ajax call to add an item to the cart */
function addToCart(productCode) {
    new Ajax.Request("/store/CartAddAjax.do", {
        method: 'post',
        parameters: "orderProductCodes=" + productCode + "&orderProductQuantities=1",
        onSuccess: function() {
            refreshMiniCart();
        },
        onFailure: function() {
            refreshMiniCart();
            alert('There was an error processing your request.');
        }
    });
}

/* variable to lock the removeFromCart ajax call */
var removeFromCartLocked = false;
/* ajax call to remove a product from the cart */
function removeFromCart(productCode, orderItemID) {
    if(!removeFromCartLocked) {
    removeFromCartLocked = true;
    new Ajax.Request("/store/CartItemEdit.do", {
        method: 'post',
        parameters: "orderItemID=" + orderItemID + "&orderProductCodes=" + productCode + "&orderProductQuantities=0",
        onSuccess: function() {
            new Effect.Fade(document.getElementById(orderItemID+"_miniCartItem"), {duration: .5});
            setTimeout("refreshMiniCart();removeFromCartLocked = false;",500);
        },
        onFailure: function() {
            refreshMiniCart();
            alert('There was an error processing your request.');
            removeFromCartLocked = false;
        }
    });
    }
}

/* disable all fields in a form */
function disableForm(form) {
    form = $(form);
    for(i=0;i<form.elements.length;i++) {
        form.elements[i].disabled = true;
    }
}

/* enable all fields in a form */
function enableForm(form) {
    form = $(form);
    for(i=0;i<form.elements.length;i++) {
        form.elements[i].disabled = false;
    }
}

/* returns true if responseText contains errors */
function responseContainsError(responseText) {
    // alert("responseError="+responseText.indexOf('<div id="errorContent">'));
    return  responseText.indexOf('<div id="errorContent">') != -1;
}

/* returns content of div with id="errorConent" in responseText */
function getResponseError(responseText) {
    var temp = responseText.split('<div id="errorContent">');
    // alert("getResponseError=\n"+temp[1].split("</div>")[0]);
    return temp[1].split("</div>")[0];
}

/* Submit a form using ajax*/
function submitAjaxForm(formElement) {
    formElement = $(formElement);
    var storeError  = $('storeError');
    // prevent a double submission
    if(!formElement.submiting) {
        formElement.submiting = true;
        // form.serialize, a prototype method, creates a map of the
        // values of the form to send as parameters in an http request.
        // Called before disabling form because disabled form fields are not serialized.
        var param = formElement.serialize(true);
        disableForm(formElement);

        var url = formElement.action;
        //formElement.disabled = true;
        url = url.substring(0, (url.length - 3)) + "Ajax.do?time=" + new Date().getTime();
        new Ajax.Request(url, {
            method: 'post',
            parameters: param,
            onSuccess: function(transport) {
                            // reset error div
                            storeError.innerHTML = "";
                            if (responseContainsError(transport.responseText)) {
                                /* HANDLE ERRORS */
                                // put error message in error div
                                var errorContent = document.createElement("div");
                                errorContent.id = "errorContent";
                                errorContent.innerHTML = getResponseError(transport.responseText);
                                var errorContentContainer = document.createElement("div");
                                errorContentContainer.id = "errorContentContainer";
                                var errorContainer = document.createElement("div");
                                errorContainer.id = "errorContainer";
                                errorContentContainer.appendChild(errorContent);
                                errorContainer.appendChild(errorContentContainer);
                                storeError.appendChild(errorContainer);
                            } else {
                                formElement.reset();
                            }
                       },
            onFailure: function() {
                            alert('Sorry, we were unable to complete your request. Please try again.');
                       },
            onComplete: function() {
                            refreshMiniCart();
                            enableForm(formElement);
                            formElement.submiting = false;
                            //formElement.elements.getElementsByName('submit')[0].disabled=false;
                        }
        });
}}


// Submit form using ajax and put the contents in the updateContainer.
// If no error is returned, the currentContainer is closed and the updateContainer is opened with new content added.
// If an error is returned, it is parsed out and put in the error container. No containers are opened or closed.
function submitFormAndUpdate(formElement, currentContainer, updateContainer, errorContainer) {
    formElement     = $(formElement);
    updateContainer = $(updateContainer);
    errorContainer  = $(errorContainer);

    // prevent a double submission
    if(!formElement.submiting) {
        formElement.submiting = true;
        disableForm(formElement);


    // Form.serialize, a prototype method, creates a map of the
    // values of the form to send as parameters in an http request
    var param = Form.serialize(formElement);
    var url = formElement.action + "?time=" + new Date().getTime();
    var noError = false;

    new Ajax.Request(url, {
        method: 'post',
        parameters: param,
        onSuccess: function(transport) {
                        errorContainer.innerHTML = "";
                        // if a page with an errorContent div element is returned, put its contents in our errorContainer
                        if(responseContainsError(transport.responseText)) {
                            /* HANDLE ERRORS */
                            //  Take the error out of the transport responseText and display in errorContainer
                            errorContainer.innerHTML = getResponseError(transport.responseText);
                            enableForm(formElement);
                        } else {
                            updateContainer.innerHTML = transport.responseText;
                            noError = true;
                        }
                   },
        onFailure: function() {
                        alert('There was an error processing your request.');
                        enableForm(formElement);
                   },
        onComplete: function() {
                        formElement.submiting = false;
                        if(noError) {
//                            toggleSlide(updateContainer);
                            toggleSlide(currentContainer, updateContainer);
                        } else {
                            /*toggleSlide(errorContainer);*/
                        }
                        //formElement.elements.getElementsByName('submit')[0].disabled=false;
                    }
    });
}

}

// Adds a method to the document object that returns an
// array of elements that have the given class name.
document.getElementsByClassName = function(clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}
// selected Payment is a global variable used in the showPayment method
var selectedPayment;
// given an id if the element with that id is not equal to the selected payment,
// "selected" is added to its className, and its id becomes the selected payment.
function showPayment(id) {
    id = $(id);
    if (selectedPayment != id) {
        $(selectedPayment).className = $(selectedPayment).className.replace(" selected", "");
        id.className = id.className + " selected";
        selectedPayment= id;
    }
/*    var paymentOptionContainers = document.getElementsByClassName('paymentOption');
    for(i=0;i<paymentOptionContainers.length;i++) {
        if($(paymentOptionContainers[i]).id == id) {
            paymentOptionContainers[i].className = paymentOptionContainers[i].className + " selected";
        } else {
            paymentOptionContainers[i].className = paymentOptionContainers[i].className.replace(" selected", "");
        }
    }*/
}

/* Greys out the background and displays a div with an id of 'lightBox' used on the thank you page*/
function grayOut() {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = (arguments.length > 0) ? arguments[0] : {};
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars
        tnode.style.cursor='pointer';                    // Let users know area is clickable
        tnode.style.display='none';                      // Start out Hidden
        //tnode.onclick = grayOut;                         // When clicked go back to the normal page
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (!dark.vis) {
    var pageWidth='100%';
    var pageHeight='100%';

    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;
    dark.style.MozOpacity=opaque;
    dark.style.filter='alpha(opacity='+opacity+')';
    dark.style.zIndex=zindex;
    dark.style.backgroundColor=bgcolor;
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';
    dark.vis = true;
  } else {
     dark.style.display='none';
      dark.vis = false;
  }

    // display light box
    var lightBox = document.getElementById("lightBox");
    lightBox.style.display =  (dark.vis) ? "block" : "none";

    // prevent scrolling
    document.body.style.overflow =  (dark.vis) ? "hidden" : "scroll";

}
// global variable used in the checkDownloadStatus() method
var downloadStatusTimer;
// Makes an ajax call to check the download status of purchased products.
// Used on thank you/invoice receitp page.
function checkDownloadStatus() {
    var downloadComplete = false;
        new Ajax.Request("/store/checkDownloadStatus.do?time=" + new Date().getTime(), {
        method: 'get',
        onSuccess: function(transport) {
            // Get JSON values
            var jsonRaw = transport.responseText;
            // Eval JSON response into variable
            var downloadStatus = eval("(" + jsonRaw + ")");
            downloadComplete = downloadStatus.downloadComplete;
           // alert("downloadComplete: " + downloadComplete);
           // if the download is complete and the page is still dark
           if(downloadComplete && $('darkenScreenObject').style.display == 'block') {
                // display close button on lightBox.
                displayComplete();
                stopCheckDownloadStatus();
            } else {
                downloadStatusTimer = setTimeout("checkDownloadStatus()",20000);
            }
        },
        onFailure: function() {
            // alert('There was an error checking the status of your download.');
            downloadStatusTimer = setTimeout("checkDownloadStatus()",20000);
        }
    });
}
/* stop checking the status of the download*/
function stopCheckDownloadStatus() {
clearTimeout(downloadStatusTimer);
}

function displayComplete() {
    /*$("lightBoxMenuMessage").innerHTML = "none";*/
    $("lightBoxCloseGrey").style.display = "none";
    $("lightBoxClose").style.display = "block";
}

/* Rico Slide Functions */
/* ToggleSlide will accept any number of elements/element ids as arguments. It will slide up or down
   based on weather the element has a showing property value of true or false. Elements will slide in the order
   they're provided.
*/
function toggleSlide() {
   if(arguments.length > 0)
   elem = $(arguments[0]);
    var args = Array.prototype.slice.call(arguments);
   if ( elem.showing )
      { slideBoxUp.apply(this, args); elem.showing = false; }
   else
      { slideBoxDown.apply(this, args); elem.showing = true; }
}

function slideBoxUp() {
    var args = Array.prototype.slice.call(arguments);
    var box = $(args.shift());
    box.style.overflow = "hidden";
    if(args.length >0) {
        new Rico.Effect.Size( box, null, 1, 1, 20, {complete:function() { toggleSlide.apply(this, args); }});
    } else {
        new Rico.Effect.Size( box, null, 1, 1, 20);
    }
}

function slideBoxDown() {
    var args = Array.prototype.slice.call(arguments);
    var box = $(args.shift());
    if(args.length >0) {
        new Rico.Effect.Size( box, null, 575, 1, 20, {complete:function() { $(box).style.overflow = "visible"; toggleSlide.apply(this, args); }});
    } else {
        new Rico.Effect.Size( box, null, 575, 1, 20, {complete:function() { $(box).style.overflow = "visible"; }});
    }
}
/* End Rico Slide Functions*/


/* method to ensure a form can only be Submited once */
function checkSubmitOnce(form) {
      if (!form.submited) {
          form.submited=true;
          //disableForm(form);
          return true;
      } else {
          return false;
      }
}

/* accept terms and conditions handles resizing the TAC container as well as updating the checkout form */
/* used on checkout page containing terms and conditions */
function acceptTermsAndConditions() {
    new Effect.BlindUp($('termsAndConditions'),{scaleTo: 33});
    $("deliveryInformationContainer").style.display = "block";
    $("billingInformationContainer").style.display = "block";
    $("shippingInformationContainer").style.display = "block";
    $("paymentInformationContainer").style.display = "block";
}

  /* checkRefieldStatus */
  /* Used in the e-score search results page. Called when user clicks an E-Score Celeb. box.
   * If the container is already expanded, the container is closed. Otherwise, an ajax call
   * is made to check the refield status of an E-Score celebrity product given it's last refield date.
   */
function checkRefieldStatus(formattedClosedDate, productId) {
    if(!escoreCelebEffectLocked){
        escoreCelebEffectLocked = true;
        if($(productId+"_detail").expanded) {
            new Effect.BlindUp(productId+"_detail", {duration:0.25, scaleTo:5, queue: {position:'end', scope: 'escoreCelebrity', limit:1},afterFinish: unlockEScoreEffect });
        } else {
            new Ajax.Request("/store/RefieldStatus.do?formattedClosedDate=" + formattedClosedDate, {
                method: 'post',
                onSuccess: function(transport) {
                    // Get JSON values
                    var jsonRaw = transport.responseText;
                    // Eval JSON response into variable
                    var refieldStatus = eval("(" + jsonRaw + ")");
                    //var isFreeRefield = refieldStatus.isFreeRefield;
                    displayRefieldAttribute(refieldStatus.isFreeRefield, productId);
                }
            });
        }
    }
}

/* displayRefieldAttribute */
/* Used in the e-score search results page. Called from checkRefieldStatus function
 * displays the appropriate product attribute based on the isisFreeRefield and productDetailsId parameters.
 */
function displayRefieldAttribute(isFreeRefield, productId) {
    var refieldAttributeId = isFreeRefield ? productId+"|refield_escore_refield_escore_free" : productId+"|refield_escore_refield_escore_charge";
    if(document.getElementById(refieldAttributeId)) {
        $(refieldAttributeId).style.display = "block";
        new Effect.BlindDown(productId+"_detail", {duration:0.25, scaleFrom:5, queue: {position:'end', scope: 'escoreCelebrity', limit:1},afterFinish: unlockEScoreEffect });
    } else {
        escoreCelebEffectLocked = false;
    }
}

function unlockEScoreEffect(obj) {
    escoreCelebEffectLocked = false;
    obj.element.expanded = !obj.element.expanded;
}

// used to lock escore celeb search effect (blind up and blind down)
var escoreCelebEffectLocked = false;


// removes leading and trailing spaces from a string
// todo: remove when upgrading prototype
String.prototype.strip = function() {
	return this.replace(/^\s+|\s+$/g,"");
}



