/**
 * Utility methods.
 */


isEmailValid = function(value) {
     // by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
     return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

isUrlValid = function(value) {
            // adapted from code by Scott Gonzalez: http://projects.scottsplayground.com/iri/
    return /^(https?):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}

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

$.fn.resizeImages=function(a){var d=Math.ceil;if(a==null)a=200;var e=a,f=a;$(this).each(function(){var b=$(this).height(),c=$(this).width();if(b>c)f=d(c/b*a);else e=d(b/c*a);$(this).css({height:e,width:f})})};

DSresizeImages=function(a){var d=Math.ceil;if(a==null)a=200;var e=a,f=a;$(this).each(function(){var b=$(this).height(),c=$(this).width();if(b>c)f=d(c/b*a);else e=d(b/c*a);$(this).css({height:e,width:f})})};

$.fn.resizeImages=function(maxW, maxH){
   dsLog("Resizing to " + maxW + "x" + maxH + " size");
   $(this).each(function() {
       dsLog("Found an image");
       var height = $(this).height();
       var width = $(this).width();
       dsLog("Existing size: to " + width + " x " + height);

       var dimensions = dsScaleSize(maxW, maxH, width, height);
       var newWidth = dimensions[0];
       var newHeight = dimensions[1];
       var newWidth = 40;
       var newHeight = 40;
       dsLog("Resizing to " + newWidth + " x " + newHeight);
       $(this).css({height: newHeight, width: newWidth});

   });
}

extractId = function(str) {
   if (str && str.trim() !== '') {
     var items = str.split("_",2);
     return (items[1]);
   }
   return "";
}

dsScaleSize = function(maxW, maxH, currW, currH){

        var ratio = currH / currW;

        if(currW >= maxW && ratio <= 1){
            currW = maxW;
            currH = currW * ratio;
        }
        else if(currH >= maxH){
           currH = maxH;
           currW = currH / ratio;
        }

        return [currW, currH];
    }


showWarningDialog = function(title, message) {
    $("#dsWarningDialog").remove();
    $('<div id="dsWarningDialog">' + message + '</div>').dialog({
       title: '<div class="ds-warning-icon"> ' + title + '</div>',
       autoOpen: true,
       modal: false,
       resizable: false,
       buttons: {
           "Ok": function() {
                $( this ).dialog( "close" );
            }
       }
    });
}

isAjaxError = function (data, textStatus, request) { 
    if (data && data.responseCode && data.responseCode != 200 ) {
        return true;
    }
    if (data && (data.success == false || data.success == "false"))  {
        return true;
    }
    if (data && data.notLoggedIn) {
        return true;
    }
}

initializeMaskDialog = function() {
    dsLog("Initializing dialog now...");

    $("#maskDialog").dialog({
      autoOpen: false,
      closeOnEscape: false,
      resizable: false,
      title: '<div id="maskTitle"></div>',
      modal: true,
      width: 300,
      height: 50,
      open: function(event, ui) { 
          $(".ui-dialog-titlebar-close").hide(); 
      }
    });
}

mask = function(title, message, config) {
    unmask();
    var icon = "ds-hourglass-icon";
    if (config) {
       if (config.width) { width = config.width; }
       if (config.icon) { icon = config.icon; }
       if (config.height) { height = config.height; }
    }

    $("#maskDialog").html(message);
    $("#maskTitle").attr("class", icon);
    dsLog("Opening dialog now...");
    $("#maskDialog").dialog("open");

}

unmask = function() {
    dsLog("Closing dialog now...");
    if ($("#maskDialog").dialog("isOpen")) {
        $("#maskDialog").dialog("close");
    }
}

alertDialog = function(title, message, scope, config) {
    var sc = scope;
    var width = 330;
    var height = 120;
    var icon = "ds-warning-icon";
    if (config) {
       if (config.width) { width = config.width; }
       if (config.icon) { icon = config.icon; }
       if (config.height) { height = config.height; }
    }
    var closeFn = config.close;

        $("<div>" + message + "</div>").dialog({
            autoOpen: true, modal: true, resizable: false, context: this,
            width:    width, height:   height,
            title: '<div id="alertDialog" class="' + icon + '"> ' + title + '</div>',
            beforeClose: function(event, ui) {
               if (closeFn) {
                   closeFn.apply(sc);
               }
            },
            buttons: {
                "Ok": function() {
                    $( this ).dialog( "close" );
                }
                
            }
        });

}

yesNoDialog = function(title, message, scope, config) {
    var sc = scope;
    var width = 330;
    var height = 120;
    var icon = "ds-warning-icon";
    if (config) {
       if (config.width) { width = config.width; }
       if (config.icon) { icon = config.icon; }
       if (config.height) { height = config.height; }
    }
    var yesFn = config.yes;
    var noFn = config.no;

        $("<div>" + message + "</div>").dialog({
            autoOpen: true,
            modal: true,
            resizable: false,
            context: this,
            width:    width,
            height:   height,
            title: '<div id="yesNoDialog" class="' + icon + '"> ' + title + '</div>',
            buttons: {
                "Yes": function() {
                    dsLog("User clicked yes");
                    if (yesFn) {
                        yesFn.apply(sc);
                    }
                    $( this ).dialog( "close" );
                },
                "No": function() {
                    dsLog("User clicked no");
                    if (noFn) {
                        noFn.apply(sc);
                    }
                    $( this ).dialog( "close" );
                }
            }
        });
}

checkAjaxResponseForExpiredSession = function(textMessage, errorData) {
    var sessionExpired = 0;
    dsLog(" --- Checking for expired session");
    if (errorData.data && errorData.data.notLoggedIn) {
        unmask();
        dsLog("Session was expired!");
        sessionExpired = 1;
        $("<div>Sorry, your DearSanta.com session has ended<br/>"
         + "due to inactivity."
         + "<br/><br/>"
         + "Please log in to continue using the site."
         + "</div>").dialog({
             title: '<div class="ds-group-icon"> Your are logged out.</div>',
             autoOpen: true,
             modal: true,
             resizable: false,
             buttons: {
                "Log In Now": function() {
                    window.location=DS_BASE_DIR;
                }
             }
        });

    }
    return sessionExpired;

}

showAjaxError = function(textMessage, errorData) {
    dsLog("errorData.data.reason = " + errorData.data.reason);
    dsLog("errorData.textStatus = " + errorData.textStatus);
    dsLog("errorData.responseCode = " + errorData.responseCode);
    if (!checkAjaxResponseForExpiredSession(textMessage, errorData)) {
        var myReason = "";
        if (!isBlankString(errorData.data) && !isBlankString(errorData.data.reason)) {
            myReason = myReason
                + $('<div/>').html(errorData.data.reason).html() 
                + "<br/>";
        }
        if (!isBlankString(errorData.textStatus) && errorData.textStatus != "success") {
            myReason = myReason  
                + $('<div/>').html(errorData.textStatus).html() 
                + "<br/>";
        }
        if (!isBlankString(errorData.responseCode)) {
            myReason = myReason + "Response Code: " + errorData.responseCode + "<br/>";
        }
        unmask();
        $("<div>" + textMessage + ".<br/><br/>Reason: " +
           myReason
        + "</div>").dialog({
             title: '<div class="ds-warning-icon"> Error</div>',
             autoOpen: true,
             modal: true,
             resizable: false
        });

    }

}

isBlankString = function(str) {
   var isBlank = (typeof str === 'undefined' || str == null || str == '');
   dsLog("type = " + typeof str + ", blank=" + isBlank + " str=" + str);
   return isBlank;
}


dsLog = function(msg) {
    // if (Ext.isGecko) {
    if(window.console){
            try {
                //console.log(msg); // Causes a script error, even in Firefox?
            }
            catch (err) {
                // ignore errors.
            }
    }
}

