// PHP.js
// Library of standard PHP functions
// More at: http://phpjs.org/functions/explode

function getGlobalData(storeKey) {
  var globalDiv = $("body");
  return(globalDiv.data(storeKey));
}

function storeGlobalData(storeKey, storeData) {
  var globalDiv = $("body");
  if (storeData == undefined) {
      globalDiv.removeData(storeKey);
  } else {
      globalDiv.data(storeKey, storeData);
  }
}

function safelog(msg) {
    console.log(msg);		// now that i'm using the debug plugin, MSIE can show errors!
}


function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function trim (str, charlist) {
    // Strips whitespace from the beginning and end of a string  
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function is_numeric( mixed_var ) {
    // Returns true if value is a number or a numeric string  
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    return !isNaN(mixed_var * 1);
}

function substr( f_string, f_start, f_length ) {
    // Returns part of a string  
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
    f_string += '';

    if(f_start < 0) {
        f_start += f_string.length;
    }

    if(f_length == undefined) {
        f_length = f_string.length;
    } else if(f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if(f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}

function rawurlencode( str ) {
    // URL-encodes string  
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin van Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
 
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urldecode.
    // Note that I hacked on this from the original source, which had
    // for (search in histogram) {
    // which does not compile in IE7!!!

    var histogram_keys, histogram_vals;
    histogram_keys = []; 
    histogram_keys.push("'");
    histogram_keys.push('(');
    histogram_keys.push(')');
    histogram_keys.push('*');
    histogram_keys.push('~');
    histogram_keys.push('!');
    histogram_keys.push('\u20AC');
    histogram_keys.push('\u0081');
    histogram_keys.push('\u201A');
    histogram_keys.push('\u0192');
    histogram_keys.push('\u201E');
    histogram_keys.push('\u2026');
    histogram_keys.push('\u2020');
    histogram_keys.push('\u2021');
    histogram_keys.push('\u02C6');
    histogram_keys.push('\u2030');
    histogram_keys.push('\u0160');
    histogram_keys.push('\u2039');
    histogram_keys.push('\u0152');
    histogram_keys.push('\u008D');
    histogram_keys.push('\u017D');
    histogram_keys.push('\u008F');
    histogram_keys.push('\u0090');
    histogram_keys.push('\u2018');
    histogram_keys.push('\u2019');
    histogram_keys.push('\u201C');
    histogram_keys.push('\u201D');
    histogram_keys.push('\u2022');
    histogram_keys.push('\u2013');
    histogram_keys.push('\u2014');
    histogram_keys.push('\u02DC');
    histogram_keys.push('\u2122');
    histogram_keys.push('\u0161');
    histogram_keys.push('\u203A');
    histogram_keys.push('\u0153');
    histogram_keys.push('\u009D');
    histogram_keys.push('\u017E');
    histogram_keys.push('\u0178');

    histogram_vals = [];    
    histogram_vals.push('%27');
    histogram_vals.push('%28');
    histogram_vals.push('%29');
    histogram_vals.push('%2A');
    histogram_vals.push('%7E');
    histogram_vals.push('%21');
    histogram_vals.push('%80');
    histogram_vals.push('%81');
    histogram_vals.push('%82');
    histogram_vals.push('%83');
    histogram_vals.push('%84');
    histogram_vals.push('%85');
    histogram_vals.push('%86');
    histogram_vals.push('%87');
    histogram_vals.push('%88');
    histogram_vals.push('%89');
    histogram_vals.push('%8A');
    histogram_vals.push('%8B');
    histogram_vals.push('%8C');
    histogram_vals.push('%8D');
    histogram_vals.push('%8E');
    histogram_vals.push('%8F');
    histogram_vals.push('%90');
    histogram_vals.push('%91');
    histogram_vals.push('%92');
    histogram_vals.push('%93');
    histogram_vals.push('%94');
    histogram_vals.push('%95');
    histogram_vals.push('%96');
    histogram_vals.push('%97');
    histogram_vals.push('%98');
    histogram_vals.push('%99');
    histogram_vals.push('%9A');
    histogram_vals.push('%9B');
    histogram_vals.push('%9C');
    histogram_vals.push('%9D');
    histogram_vals.push('%9E');
    histogram_vals.push('%9F');


    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);

    // Restore spaces, converted by encodeURIComponent which is not rawurlencode compatible
    ret = replacer('%20', ' ', ret); // Custom replace. No regexing

    var i, search;
    for (i = 0; i < histogram_keys.length; ++i) {
	search = histogram_keys[i];
        replace = histogram_vals[i];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });

    return ret;
}

// Code lifted from: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_urldecode/

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

// From http://www.ajaxdr.com/c/javascript/
function js_money(v) {
    v += '';
    var d,c;
    if(v.indexOf('.') > -1) {
	d=v.split('.')[0].toString();
	c=v.split('.')[1].toString();
    }else {
	d=v.toString();
	c='0';
    }     if(c.length==1)
	      return d+'.'+c+'0';
    else if(c.length==2)
	return d+'.'+c;
    else if(c.length>2)
	return d+'.'+Math.round(parseFloat((c.substr(0,2)+'.'+c.substr(2))));
    else
	return d+'.'+'00';
}

