var KEY_ENTER = 13;

function removeUserFromCookie(user, userCookieKey, userSplit, attrSplit) {
    var rawUsers = $.cookie(userCookieKey);
    var users = $().crypt({method : 'b64dec', source: rawUsers});
    var splitUsers = users.split(";");
    var backUsers = '';
    for (var i = 0; i < splitUsers.length; i++) {
        var oneSplit = splitUsers[i].split(userSplit);
        if (oneSplit.length == 4 && user == oneSplit[0]) {

        } else if (oneSplit.length == 4) {
            backUsers += splitUsers[i] + attrSplit;
        }
    }
    var rawBackUsers = '';
    try {
        if (backUsers != '') {
            rawBackUsers = $().crypt({method: 'b64enc', source: backUsers});
            rawBackUsers = rawBackUsers.replace('==', '**');
            rawBackUsers = rawBackUsers.replace('=', '*');
        }
    } catch(ex) {
        // nothing with this
    }
    $.cookie(userCookieKey, rawBackUsers);
}

function containsInternalError(responseText) {
    if (responseText != null && (responseText.indexOf("internalError.action?_eventName=view") >= 0)) {
        $("#layoutContainer").html(responseText);
        return true;

    } else {
        return false;
    }
}

function submitForm(formId, resultContainerId, callback) {
	$("#" + formId).ajaxForm({
        beforeSend: function() {
            lockScreenWait();
        },
        success: function(responseText) {
            if (!containsInternalError(responseText)) {
                if ((callback) && (!containsErrors(responseText))) {
    
                    callback(responseText);
                } else {
                	if (resultContainerId != null) {
                		$("#" + resultContainerId).html(responseText);
                	}
                }
                unlockScreen();
            }
        },
        error: handleInternalError
    });
    $("#" + formId).submit();
}

function ajaxSubmitToEvent(formId, eventName, resultContainerId, callback) {
    $("#" + formId + " > [name=_eventName]").val(eventName);
    submitForm(formId, resultContainerId, callback);
}

function submitToEvent(formId, eventName) {
    $("#" + formId + " > [name=_eventName]").val(eventName);
    $("#" + formId).submit();
}

/**
 * The purpose of this method is to allow you to submit parts of a form separately.
 *
 * This method retreives all form elements stored in 'formElementsContainerId' and makes an ajax request to 'url'.
 * If a callback method is provided will be called with the response output otherwise the response will be placed on
 * the provided form elements container.
 *
 * This method handles the locking of the screen.
 */
function submitPartialForm(url, formElementsContainerId, callback, keepLock) {
    if ($("#" + formElementsContainerId).size() == 0) {
        alert(getString("submitError.submitPartialForm") + " " + formElementsContainerId);
    } else {
        //form to array extracts an array of form elements from a container
        var data = $("#" + formElementsContainerId).formToArray(true);

        jQuery.ajax({
            url: $.eflorist.context + url,
            data: data,
            cache: false,
            beforeSend: function() {
                lockScreenWait();
            },
            success: function(responseText) {
                if (!containsInternalError(responseText)) {
                    if (callback) {
                        callback(responseText);

                    } else {
                        $("#" + formElementsContainerId).html(responseText);
                    }
                    if( keepLock == null ) { 
	                	// if we have a submitPartialForm and then a openAjaxDialog in the callback
	                	// like in openProductsDialog function
	                	// then the following unlockScreen happens after the lockScreenWait of the openAjaxDialog function ,
	                	// and the screen will be unlocked . So in this case we will not unlock the screen
	                	unlockScreen();
	                }
                }
            },
            error: handleInternalError
        });
    }
}

function doRedirect(url) {
    window.location.href = $.eflorist.context + url;
}

//todo remove this method - brings more problems than it solves
/**
 * This purpose of this method is to perform an ajax request but not to use the output of the server. This is usefull
 * when you want to persist something on the server and you will hande the UI modifications related to that persistance
 * using only client side code.
 *
 * This method handles the locking of the screen.
 */
function ajaxCallWithNoOutput(url, callback) {
    jQuery.ajax({
        url: $.eflorist.context + url,
        cache: false,
        beforeSend:function() {
            lockScreenWait();
        },
        success: function(responseText) {
            if (!containsInternalError(responseText)) {
                if (callback) {
                    callback(responseText);
                }
                unlockScreen();
            }
        },
        error: handleInternalError
    });
}

function changeLinksForSubsetsPaged(containerId, blockedContainerId) {
    var selector = '#' + containerId + ' div.paginate-links > a';
    $(selector).each(function() {
        var linkData = $(this).attr("href");
        if (linkData != null) {
            var queryArr = linkData.split("?");
            var action = queryArr[0];
            var queryStr = queryArr[1];
            $(this).attr("href", "javascript:doAjaxForSubsets('" + action + "', '" + queryStr + "', '" + containerId + "' , '" + blockedContainerId + "');");
        }
    });
}

function doAjaxForSubsets(url, data, containerId, blockedContainerId) {
    $.ajax({
        url: url,
        data: data,
        cache: false,
        beforeSend: function() {
            lockScreenWait();
        },
        success: function(responseText) {
            if (!containsInternalError(responseText)) {
                $('#' + containerId).html(responseText);
                //            changeLinksForSubsetsPaged(containerId, blockedContainerId);
                unlockScreen();
            }
        },
        error: handleInternalError
    });
}

function lastSubString(str, delim) {
    return str.substring(str.indexOf(delim) + 1);
}

function openAjaxDialog(url, properties) {
    lockScreenWait();
    $("#efloristInternal_dialog").dialog('option', 'buttons', null);
    if (properties != null) {
        $("#efloristInternal_dialog").dialog("option", properties);
    }
    jQuery.ajax({type: "GET", url: $.eflorist.context + url, cache: false,
        success: function(data, textStatus) {
            if (!containsInternalError(data)) {
                $("#efloristInternal_dialog").html(data);
                $("#efloristInternal_dialog").dialog("open");
                unlockScreen();
            }
        },
        error: handleInternalError
    });
}

function closeAjaxDialog() {
    $("#efloristInternal_dialog").dialog("close");
}

function ajaxLoad(containerId, url, callback) {
    lockScreenWait();
    jQuery.ajax({type: "GET", url: $.eflorist.context + url, cache: false,
        success: function(data, textStatus) {
            if (!containsInternalError(data)) {
                $("#" + containerId).html(data);
                unlockScreen();
                if (callback != null) {
                    callback();
                }
            }
        },
        error: handleInternalError
    });
}

//this initialize array remove element
function applyRemoveMethodToArray(array) {
    array.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    }
}

/**
 * Disables all fields. If you want also to disabled hidden fields you need to specify explicitly.
 */
function disableFormFields(containerId, includeHiddens) {
    if (includeHiddens) {
        $("#" + containerId + " input, #" + containerId + " select, #" + containerId + " textarea").attr("disabled", "disabled");

    } else {
        $("#" + containerId + " input:visible, #" + containerId + " select:visible, #" + containerId + " textarea:visible").attr("disabled", "disabled");
    }
}

/**
 * Enables all fields. If you want also to enabled hidden fields(probabily disabled with previous method) you need to specify explicitly.
 */
function enableFormFields(containerId, includeHiddens) {
    if (includeHiddens) {
        $("#" + containerId + " input, #" + containerId + " select, #" + containerId + " textarea").removeAttr("disabled");

    } else {
        $("#" + containerId + " input:visible, #" + containerId + " select:visible, #" + containerId + " textarea:visible").removeAttr("disabled");
    }
}

function disableMarkedFormFields(containerId, markerClass) {
    if (!markerClass) {
        markerClass = "disableFormField";
    }

    $("#" + containerId + " ." + markerClass).attr("disabled", "disabled");
}

function enableMarkedFormFields(containerId, markerClass) {
    if (!markerClass) {
        markerClass = "disableFormField";
    }

    $("#" + containerId + " ." + markerClass).removeAttr("disabled");
}

function hideMarkedFields(containerId, allocateSpace, markerClass) {
    if (!markerClass) {
        markerClass = "hideField";
    }

    if (allocateSpace) {
        $("#" + containerId + " ." + markerClass).css("visibility", "hidden");

    } else {
        $("#" + containerId + " ." + markerClass).hide();
    }
}

function showMarkedFields(containerId, allocateSpace, markerClass) {
    if (!markerClass) {
        markerClass = "hideField";
    }

    if (allocateSpace) {
        $("#" + containerId + " ." + markerClass).css("visibility", "visible");

    } else {
        $("#" + containerId + " ." + markerClass).show();
    }
}

function toggleButtonEnable(eButtonId) {
    $("#" + eButtonId + "_enabled").toggle();
    $("#" + eButtonId + "_disabled").toggle();
}

function enableButton(eButtonId) {
    $("#" + eButtonId + "_enabled").show();
    $("#" + eButtonId + "_disabled").hide();
}

function disableButton(eButtonId) {
    $("#" + eButtonId + "_enabled").hide();
    $("#" + eButtonId + "_disabled").show();
}

function setButtonEnabled(eButtonId, enabled) {
    if (enabled) {
        enableButton(eButtonId);
    } else {
        disableButton(eButtonId);
    }
}

function setButtonText(buttonId, text) {
    $("#" + buttonId + "_enabled > span").html("<em></em>" + text);
    $("#" + buttonId + "_disabled > span").html("<em></em>" + text);
}

function enableElement(elementId) {
    $("#" + elementId).removeAttr("disabled");
}

function disableElement(elementId) {
    $("#" + elementId).attr("disabled", "disabled");
}

function confirmAction(titleKey, msgKey, yesCallback, noCallback, yesKey, noKey) {
    confirmActionText(getString(titleKey), getString(msgKey), yesCallback, noCallback,
            yesKey ? getString(yesKey): getString("common.yes"),
            noKey ? getString(noKey) : getString("common.no"));
}

function confirmActionText(title, msg, yesCallback, noCallback, yes, no) {
    var dialogButtons = {};
    
    yes = yes ? yes: getString("common.yes");
    no = no ? no : getString("common.no");
    
    dialogButtons[no] = function() {
        closeAjaxDialog();
        if (noCallback) noCallback();
    };
    dialogButtons[yes] = function() {
        closeAjaxDialog();
        yesCallback();
    };

    $("#efloristInternal_dialog").html("<div class='confirmDialog'>" + escapeHtml(msg) + "</div>");
    $("#efloristInternal_dialog").dialog('option', 'title', title);
    $("#efloristInternal_dialog").dialog('option', 'buttons', dialogButtons);
    $("#efloristInternal_dialog").dialog('option', {minHeight: 150, minWidth: 0, width: 500});
    $("#efloristInternal_dialog").dialog('open');
}

function lockScreen(containerId, messageKey) {
    var id = containerId != null ? containerId : "layoutContainer";
    var msg = messageKey != null ? getString(messageKey) : "";
    $('#' + id).block({
        fadeIn: 0,
        fadeOut: 0,
        message: '<h2 class="noBackground">' + msg + '</h2>',
        css: {
            border: 'none',
            padding: '7px',
            backgroundColor: '#C2DDEF',
            '-webkit-border-radius': '5px',
            '-moz-border-radius': '5px',
            'font-size': '12px',
            color: '#000',
            cursor: 'default'
        },
        overlayCSS:  {
            backgroundColor: '#555555',
            opacity: '0.5',
            cursor: 'default'
        }
    });
}

function lockScreenWait(containerId, messageKey) {
    var id = containerId != null ? containerId : "layoutContainer";
    var msg = messageKey != null ? getString(messageKey) : getString("common.loading");
    $('#' + id).block({
        fadeIn: 0,
        fadeOut: 0,
        message: '<h2>' + msg + '</h2>',
        css: {
            border: 'none',
            padding: '7px',
            backgroundColor: '#C2DDEF',
            '-webkit-border-radius': '5px',
            '-moz-border-radius': '5px',
            'font-size': '12px',
            color: '#000'
        },
        overlayCSS:  {
            backgroundColor: '#555555',
            opacity: '0.5'
        }
    });
}

function unlockScreen(containerId) {
    var id = containerId != null ? containerId : "layoutContainer";
    $("#" + id).unblock({fadeOut: 0});
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function performQASSearch(containerId, criteriaFieldId, callbackName) {
    lockScreenWait();
    var url = '/common/searchQASAddress.action?_eventName=initialSearch';
    url += '&qasSearchCriteria=' + escape(trim($("#" + criteriaFieldId).val()));
    url += '&callbackName=' + callbackName;
    openAjaxDialog(url, {width: 600, minHeight: 460, title: getString("qas.addressSearch.title")});
}

function initCharacterCount(textAreaId, limit, countContainer) {
    characterCount(textAreaId, limit, countContainer);
    $('#' + textAreaId).bind('keyup click blur focus change paste', function() {
        characterCount(textAreaId, limit, countContainer);
    });
}

function characterCount(textAreaId, limit, countContainer) {
    var text = $('#' + textAreaId).val();
    var textlength = text.length;
    if (textlength > limit) {
        $('#' + countContainer).html(0 + '/' + limit);
        $('#' + textAreaId).val(text.substr(0, limit));
        return false;
    }
    else {
        $('#' + countContainer).html(limit - textlength + '/' + limit);
        return true;
    }
}

//function formatPrice(value) {
//    value = value.replace(",", ".");
//    value = value.replace("�", "");
//    value = value.replace("$", "");
//    value = value.replace("�", "");
//    value = value.replace(" ", "");
//
//    value = Math.round(parseFloat(value) * 100) / 100;
//
//    if (isNaN(value)) {
//        return "0.00";
//
//    } else {
//        value = value.toString();
//        if (value.substr(value.length - 2, 1) == ".") {
//            value = value + "0";
//
//        } else if (value.substr(value.length - 3, 1) != ".") {
//            value = value + ".00";
//        }
//        return value;
//    }
//}

function isEmpty(obj) {
    if (typeof(obj) == "string") {
        return obj == "";

    } else {
        return obj == null;
    }
}

//This was intended to be used when searching for an error in a response text before binding the content into dom
function containsErrors(text) {
    text = String(text);
    return text && (text.length > 0) && $(text).find("span.errorMessage").size() > 0;
}

function containsMessages(text) {
    text = String(text);
    return text && (text.length > 0) && $(text).find("span.errorWarning").size() > 0;
}

function loadDeliveryAreas() {
    window.open($.eflorist.context + "/member/account/deliveryAreas.action?_eventName=view", "viewDeliveryAreas", "width=850,height=600, screenX=150, screenY=80, scrollbars=1, resizable=yes");
}

function handleInternalError() {
    tryLogout();
    showInternalErrorDialog();
}

function showInternalErrorDialog() {
    var dialogButtons = {};
    dialogButtons[getString("common.ok")] = function() {
        closeAjaxDialog();
        doRedirect("/");
    };

    $("#efloristInternal_dialog").html("<div class='internalErrorDialog'>" + getString("systemError.internalError") + "</div>");
    $("#efloristInternal_dialog").dialog('option', 'title', getString("systemError.title"));
    $("#efloristInternal_dialog").dialog('option', 'buttons', dialogButtons);
    $("#efloristInternal_dialog").dialog('option', {minHeight: 150, width: 500, height: 150});
    $("#efloristInternal_dialog").dialog('open');
}

function showApplicationErrorDialog(errorMessage) {
    var dialogButtons = {};
    dialogButtons[getString("common.ok")] = function() {
        closeAjaxDialog();
    };

    $("#efloristInternal_dialog").html("<div class='internalErrorDialog'>" + escapeHtml(errorMessage) + "</div>");
    $("#efloristInternal_dialog").dialog('option', 'title', getString("applicationError.title"));
    $("#efloristInternal_dialog").dialog('option', 'buttons', dialogButtons);
    $("#efloristInternal_dialog").dialog('option', {minHeight: 150, width: 500, height: 200});
    $("#efloristInternal_dialog").dialog('open');
}

function showInformationDialog(errorMessage) {
    var dialogButtons = {};
    dialogButtons[getString("common.ok")] = function() {
        closeAjaxDialog();
    };

    $("#efloristInternal_dialog").html("<div class='confirmDialog'>" + escapeHtml(errorMessage) + "</div>");
    $("#efloristInternal_dialog").dialog('option', 'title', getString("common.information"));
    $("#efloristInternal_dialog").dialog('option', 'buttons', dialogButtons);
    $("#efloristInternal_dialog").dialog('option', {minHeight: 150, width: 500, height: 200});
    $("#efloristInternal_dialog").dialog('open');
}

/*
 * This method blocks the screen. The callback must manage the unblocking.
 */
function checkLockedOrder(orderId, callback) {
    jQuery.ajax({
        url: $.eflorist.context + "/member/checkLockedOrder.action?_eventName=check&orderId=" + orderId,
        cache: false,
        beforeSend:function() {
            lockScreenWait();
        },
        success: function(responseText) {
            if (!containsInternalError(responseText)) {
                if (responseText == "false") {
                    callback();

                } else {
                    showApplicationErrorDialog(responseText);
                    unlockScreen();
                }
            }
        },
        error: handleInternalError
    });
}

function tryLogout() {
    // Maybe we should check the answer here
    unlockScreen();
    //we don't invalidate the session at least for now
    //jQuery.ajax({type: "GET", url: $.eflorist.context + "/logout/processLogout.action?_eventName=doLogout", cache: false });
}

function menuNavigate(actionUrl, actionParams) {
    $("#menuNavigationForm").empty();
    $("#menuNavigationForm").attr("action", $.eflorist.context + actionUrl);
    for (var paramName in actionParams) {
        $("#menuNavigationForm").append("<input type='hidden' name='" + paramName + "' value='" + actionParams[paramName] + "'>");
    }
    $("#menuNavigationForm").submit();
    return true;
}

function getResource(relativePath) {
    return $.eflorist.context + $.eflorist.resourcePath + relativePath;
}

function spellCheck(elementId) {
    // Build an array of form elements (not there values)
    var elements = new Array(0);

    // Your form elements that you want to have spell checked
    elements[elements.length] = document.getElementById(elementId);

    // Start the spell checker
    startSpellCheck($.eflorist.context + '/jsp/common/spellcheck/', elements);
}

function escapeHtml(text) {
    return text ? text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r\n/g, "<br>").replace(/\n/g, "<br>").replace(/\r/g, "<br>") : null;
}

function markErrorMessageFields() {
    var $input = $('span.errorMessage').prev(":input");
    $input.addClass('requiredField');
}

function unmarkErrorMessageFields() {
    var $input = $('span.errorMessage').prev(":input");
    $input.removeClass('requiredField');
}

function addErrorMessage(field, errorMessage) {
    $(field).after('<span class="errorMessage">' + errorMessage + '</span>');
    markErrorMessageFields();
    Eflorist.refresh();
}

function removeErrorMessages(field) {
    unmarkErrorMessageFields();
    $(field).nextAll("span.errorMessage").remove();
}

function isInteger(value) {
    return value == parseInt(value);
}

function isBrowserIE() {
    return $.browser.msie;
}

function isBrowserIE6() {
    return $.browser.msie && (parseInt($.browser.version) == 6);
}

function writeSoundTag(audioFileUrl) {
    var isIe = isBrowserIE();
    if (isIe) {
        $('#headerSound').append("<bgsound src='" + audioFileUrl + "'/>");
    } else {
        $('#headerSound').append("<embed src='" + audioFileUrl + "' autostart='true' width='0' height='0' class='soundAlert'/>");
    }
}

function submitNormalForm(formId) {
    lockScreenWait();
    $("#" + formId).submit();
}

function centerContainer(containerId) {
    $('#' + containerId).css({position: 'absolute', 'z-index': '5000', top:'50%', left:'50%', margin: '-' + ($('#' + containerId).height() / 2) + 'px 0 0 -' + ($('#' + containerId).width() / 2) + 'px'});
}

function openUrlInNewWindowOrTab(url) {
    window.open(url, "_blank");
}
