//
// MM_FormUtils.js
//
// form input validation functions
//
// Copyright (C) 2006-2007 Mixtur Interactive, Inc. All rights reserved.
// http://www.mixtur.com, 1-866-268-3994. Unlicensed use is prohibited.
//
// Mark Eissler, mark@mixtur.com
//
// $Id: MM_FormUtils.js,v 1.1 2010/05/12 19:21:11 mark Exp $
//

/*
 IMPORTANT:  This Mixtur software is supplied to you by Mixtur Interactive, Inc. ("Mixtur")
 in consideration of your agreement to the following terms, and your use, installation, 
 or modification of this Mixtur software constitutes acceptance of these terms.  If you do
 not agree with these terms, please do not use, install, or modify this Mixtur software.
 
 In consideration of your agreement to abide by the following terms, and subject to these 
 terms, Mixtur grants you a personal, non-exclusive license, under MixturÕs copyrights in 
 this original Mixtur software (the "Mixtur Software"), to use, reproduce and modify the
 Mixtur Software.
 
 IMPORTANT:  THIS AGREEMENT DOES NOT PROVIDE FOR NOR DOES IT ALLOW REDISTRIBUTION OF THIS
 MIXTUR SOFTWARE. YOU MAY NOT REDISTRIBUTE THIS SOFTWARE WITH OR WITHOUT MODIFICATIONS.

 Neither the name, trademarks, service marks or logos of Mixtur Interactive, Inc. may be 
 used to endorse or promote products derived from the Mixtur Software without specific 
 prior written permission from Mixtur. Except as expressly stated in this notice, no other
 rights or licenses, express or implied, are granted by Mixtur herein, including but not
 limited to any patent rights that may be infringed by your derivative works or by other
 works in which the Mixtur Software may be incorporated.
 
 The Mixtur Software is provided by Mixtur on an "AS IS" basis.  MIXTUR MAKES NO WARRANTIES, 
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, 
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE MIXTUR SOFTWARE OR ITS 
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL MIXTUR BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL 
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, 
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE MIXTUR SOFTWARE, HOWEVER CAUSED AND 
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR 
 OTHERWISE, EVEN IF MIXTUR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


// mmjs_VarExists
//
// Check to see if the variable that specified by the name string inVarName
// has been declared.
//
// Returns: true (1) if the variable has been declared, otherwise 0.
//
function mmjs_VarExists(inVarName) {

    var evalStr = 'window.' + inVarName;
    
    if(eval(evalStr))
        return 1;
    else
        return 0;
}


// mmjs_NameValueObj
//
function mmjs_NameValueObj(name, value) {

    this.name = name;
    this.value = value;
    
    return this;
}


// mmjs_MakePrettyFileSizeStr
//
// Creates a string for the inBytes value parameter, complete with
// the word "Bytes," "KB", MB," or "GB" as applicable.
//
function mmjs_MakePrettyFileSizeStr(inBytes) {

    var unitStr = '';
    var prettyStr = '';
    var inBytesStr = '';
 
    if(inBytes >= 1023000000) {
        unitStr = " GB";
        inBytesStr = (inBytes/1024000000).toString(10);
        var pos = inBytesStr.indexOf('.');
        prettyStr = inBytesStr.substring(0,pos+3) + unitStr;
    }

    if(inBytes < 1023000000) {
        unitStr = " MB";
        inBytesStr = (inBytes/1024000).toString(10);
        var pos = inBytesStr.indexOf('.');
        prettyStr = inBytesStr.substring(0,pos+3) + unitStr;
    }

    if(inBytes < 1023000) {
        unitStr = " KB";
        inBytesStr = (inBytes/1024).toString(10);
        var pos = inBytesStr.indexOf('.');
        prettyStr = inBytesStr.substring(0,pos) + unitStr;
    }

    if(inBytes < 1023) {
        unitStr = " Bytes";
        inBytesStr = inBytes.toString(10);
        var pos = inBytesStr.indexOf('.');
        prettyStr = inBytesStr.substring(0,pos) + unitStr;
    }
    
    return prettyStr; 
}


function mmjs_RedirectBrowserPost(url, target) {

    var f = document.createElement('form');
    var pos = url.indexOf('?');
    var params = new Array();
    if (pos < 0) {
        f.action = url;
    } else {
        f.action = url.substring(0, pos);
        var pms = url.substring(pos+1, url.length).split('&');
        for (var p = 0; p < pms.length; p++) {
            var pm = pms[p].split('=');
            var prop = '';
            if (pm.length > 0) prop = ff_trim(pm[0]);
            var val = '';
            if (pm.length > 1) val = ff_trim(unescape(pm[1]));
            if (prop!='' && val!='') params[params.length] = new Array(prop, val);
        } // for
    } // if
    f.name = 'mm_redirect';
    f.method = 'post';
    f.enctype = 'multipart/form-data';
    switch (target) {
        case 'blank' : f.target = '_blank';  break;
        case 'top'   : f.target = '_top';    break;
        case 'parent': f.target = '_parent'; break;
        default      : f.target = '_self';
    } // switch
    var p;
    for (p = 0; p < params.length; p++) {
        var e = document.createElement('input');
        e.type = 'hidden';
        e.name = params[p][0];
        e.value = params[p][1];
        f.appendChild(e);
    } // for
    document.body.appendChild(f);
    f.submit();
}


function mmjs_trim(str) {

	var n = str.length;
	
	if (n == 0) return '';
	
	var b = 0;
	var ws = ' \r\n\t';
	
	while (b<n && ws.indexOf(str.charAt(b))>=0)
	   b++;
	
	if (b == n) return '';
	
	while (ws.indexOf(str.charAt(n-1))>=0)
	   n--;
	   
	return str.substring(b,n);
	
}

// mmjs_SetupCancelEnterKey()
//
// Setup the onkeypress handler for an entire page. The handler will suppress
// all key presses of the RETURN and ENTER keys unless the cursor is in a
// form textarea or submit element.
//
function mmjs_SetupCancelEnterKey() {

    document.onkeypress = mmjs_CancelEnterKey;
}


// mmjs_CancelEnterKey()
//
// This is the onkeypress handler. You MUST call either mmjs_SetupCancelEnterKey()
// or document.onkeypress = mmjs_CancelEnterKey; in the HEAD section of a page
// in order to get this handler to intercept all keypresses for the entire page.
// Alternatively, you can configure it to be called just within a form by doing
// something like:
//      document.FORM.onkeypress = mmjs_CancelEnterKey;
//
function mmjs_CancelEnterKey(e) {

    var code;
    var status = true;
    var nav = 'moz';
    var event = e;
    var type;

    // make sure e is set to the event (it won't be if it's IE)
    if (!event) {
        event = window.event;   //for IE
        nav = 'ie';
    }
    
    //
    // get the keycode and event type
    //
    if(nav == 'ie') {
        code = event.keyCode;
        type = event.srcElement.type;   // for IE
    } else {
        code = event.which;  
        type = event.target.type;       // for other browsers
    }

    //
    // suppress the enter key unless we are in a textarea or
    // we are in a submit element.
    //
    // NOTE: Firefox sees both the Mac return and enter keys as the same
    // keycode (13) but Safari sees the return key as 13 and the enter key
    // (on the numeric keypad) as 3. We check both.
    //
    if ((code == 13 || code == 3) && type != 'textarea' && type != 'submit')
        status = false;
        
    return status;
}

// mmjs_SubmitFormByName()
//
// Submits the form specified by name. The form must have a NAME attr.
//
// Set debug to 1 to turn on debugging.
//
function mmjs_SubmitFormByName(name, debug) {

    debug == undefined ? debug = 0:debug = 1;
    
    if(name == undefined || name.length == 0) {
        
        if(debug)
            alert("Undefined form NAME attr. Can't submit.");
        
        return;
    }
    
    document.forms[name].target = '_parent';
    document.forms[name].submit();

    return;
}

// mmjs_GetQueryArgs()
//
// Extracts arguments (name/value pairs) from the query part of a url. Then
// stuffs the data into an Object so that they can be referenced like this:
//
//  www.mixtur.com/index.html?name=blah
//
//  var args = mmjs_GetQueryArgs();
//  if (args.name) name = args.name;
//
// Receive: string indicating which window to target.
//
// NOTE: Usually, the target would be the current window, in which case you
// don't need to specify the target. But if your form is in an iFrame, then
// you will need to target the parent window, so specify "parent".
//
// Returns: an object that contains properties of name/value pairs.
//
function mmjs_GetQueryArgs(target) {
    
    var args = new Object();
    var query = "";
    
    switch (target) {
        case 'parent' : query = parent.location.search.substring(1);  break;
        default       : target = this.location.search.substring(1);
    } // switch
    
    // get query string
    var pairs = query.split("&");
    
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');        // look for "name=value"
        
        // continue if not found
        if(pos == -1) continue;
        
        // get the name
        var argname = pairs[i].substring(0,pos);
        
        // get the value
        var value = pairs[i].substring(pos+1);
        
        // add to the object
        args[argname] = unescape(value);
    }
    
    return args;   
}

