/*

 js.js : A javascript utils
 Set paths to files and directories.
 Methods for special duties etc
 Required: Prototype
*/

// Version of prototype required
var prototypeJsRequiredVersion="1.6.0";

// A function like void, return nothing
function HB() {}
var _defaultSettings_= {}
//------------------------------------------------------------------------------
// App properties and directories
var gmbApp=Object.extend({
	imgDir:"/bin/images",
	iconDir:"/bin/images/icon",
	appsDir:"/bin/applications",
	jsDir:"/bin/js",
	cssDir:"/bin/css",
	plugins:"/bin/plugins",
	flashDir:"/bin/flash",
	logo:"/bin/images/logo/givemebeats_512x100.png"
},_defaultSettings_||{});

//------------------------------------------------------------------------------


/*
 js: hash method library that allows include,html,cookies,
*/
var js={}
//------------------------------------------------------------------------------

// Extend some prototype
Element.prototype.forceNumeric=function(decimal){
var verif;
var chiffres =(decimal==true)? new RegExp("[0-9\.]") : new RegExp("[0-9]"); // Select decimal or integer vlaues
var points = 0;
	for(x = 0; x < $(this).value.length; x++){
		verif = chiffres.test($(this).value.charAt(x));
        
		if($(this).value.charAt(x) == ".")
            points++;
       
		if(points > 1){
            verif = false; 
            points = 1;
        }
        
		if(verif == false){
            $(this).value = $(this).value.substr(0,x) + $(this).value.substr(x+1,$(this).value.length-x+1);
            x--;
        }
	}
   return this;
}


// Format number to currency. Scriptaculous
function toCurrency (amount){
 
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
Element.prototype.toCurrency =  function(){

   if($(this).value!=undefined)
    $(this).value = toCurrency($F(this))
   else
    $(this).update(toCurrency($(this).innerHTML))

  return this;
}

//------------------------------------------------------------------------------
// How many seconds since 1970. Good to update URL for ajax
function timeStamp(){
odate_now = new Date();
return (odate_now.getTime());
}


// To prevent robot from reading the emaill
function gmb_makeAntiSpamEmail(user){
 document.write(user+"@"+gmbApp.siteDomain);
}


//------------------------------------------------------------------------------
// Trouble Ticket, technically send mail to admin :)
function newTroubleTicket(subject){
 var tt=gmbApp.basePath+"/account/account/?do=mails&a=p&to=nw4fzxxy1l5zmi&subject="+subject;
 location.href=tt;
}
//------------------------------------------------------------------------------
// To submit once
function submitOnce(theform){
	if (document.all||document.getElementById){
	   for (i=0;i<theform.length;i++){
	        var tempobj=theform.elements[i];
	        if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset"||tempobj.type.toLowerCase()=="button")
	        tempobj.disabled=true;
	    }
	 }
}
//------------------------------------------------------------------------------
// Pass any script
function jsOnLoad(scripts){
   Event.observe(window, 'load',function(){ eval(scripts); });
}
//To clear load event
function myUnLoad(){
  Event.unloadCache();
}
//------------------------------------------------------------------------------
// Tp validate email
function validateEmail(str){
  with (str){
     apos=str.indexOf("@");
     dotpos=str.lastIndexOf(".");
       if (apos<1||dotpos-apos<2){
	     return false
	   }
       else return true;
   }
}
//------------------------------------------------------------------------------
// Format number to currency. Scriptaculous
function currency(amount){
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
//------------------------------------------------------------------------------
// Format number
function numberFormat(nStr) {
 nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  return x1 + x2;
}
//------------------------------------------------------------------------------
// Count total words
function countWords (this_field) {
  var char_count = this_field.length;
  var fullStr = this_field + " ";
  var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
  var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
  var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
  var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
  var splitString = cleanedStr.split(" ");
  var word_count = splitString.length -1;

if (fullStr.length <2) word_count = 0;

return word_count;
}
//------------------------------------------------------------------------------
// Uppercase
String.prototype.ucwords = function(){
        return this.toLowerCase().replace(/^(.)|\s(.)/g,function($1){
		 return $1.toUpperCase();
		})
}
String.prototype.ucfirst = function(){
        return this.charAt(0).toUpperCase()+this.substr(1,this.length-1)
}

// Clean the input of a user
String.prototype.cleanInput=function(){
 return this.strip().stripScripts().stripTags();
}
/* ----------------------------------------- */
//--- ENCODE & DECODE URL
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}
//------------------------------------------------------------------------------
// Limit the max length of a field
function inputMaxLen(zone,mmax){
 if(zone.value.length>=mmax)  zone.value=zone.value.substring(0,mmax);
}
//------------------------------------------------------------------------------
// To jump to the next field automatically once max_len is reached */
function fieldToFieldFocus(field_id,max_len,next_field_id){
  if($(field_id)){
      if($(field_id).value.length>max_len) $(field_id).value=$(field_id).value.substring(0,max_len);
      if($(next_field_id) && $(field_id).value.length==max_len) $(next_field_id).activate();
  }
}


//------------------------------------------------------------------------------
// To bookmark in user browser
function bookmarkUrl(url,title){
	if (document.all)window.external.AddFavorite(url, title);
	else if (window.sidebar)window.sidebar.addPanel(title, url, "");
}


//------------------------------------------------------------------------------
// To convert version string to numbers
function convertVersionString(versionString){
  var r = versionString.split('.');
  return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Now check the version of prototype
 if(convertVersionString(Prototype.Version) < convertVersionString(prototypeJsRequiredVersion))
       throw("GMB_Framework requires the Prototype JavaScript framework >= " + prototypeJsRequiredVersion);

// Click to action
var CTA = {

  open:function(){
      Lightview.show({
        href:"#CTA",
        rel:"inline",
        title:"",
        options:{autosize:true,width:800,height:725}
      })
  },


  send:function(){
  
    $("CTA_Form").request();
    
      Lightview.show({
        href:"#CTA-Thanx",
        rel:"inline",
        title:"",
        options:{autosize:true}
      })
  }

}

var Checkout = {
	
submit:function(){
 	if($F("select-checkout-option")==undefined)
	  alert("Select an amount you want to pay")
	
	else if($F("select-checkout-option")=="15" && !$F("input-other-amount"))
	  aler("Please enter a different amount")
	
	else
	 $("DPSL_Checkout_Form").submit();
	
}	
	
}
Event.observe(window,"load",function(){
  if($("checkout-page")){
	
	$("input-other-amount").value="0.0";
	
	$("select-checkout-option").observe("change",function(){

	  if($F("select-checkout-option") !=15 )
			$("input-other-amount").value="0.0";
	})

	$("link-checkout-submit").observe("click",Checkout.submit) 
	
	$("input-other-amount").observe("click",function(){$("select-checkout-option").value=15}).observe("keyup",function(){$(this).forceNumeric(true,2)}).observe("blur",function(){this.toCurrency();})
 
   }	
})
