/**
 * utility.js
 * Javascript to manage form fields attributes and behaviours
 */
 
$(document).ready(function() {
	jqueryExtendedFunctions();
});

/** 
 * Console debugging. Levels:
 * 0 - no debugging
 * 1 - everything
 * 2 - exclude play (launcher debugs)
 */
var debugLevel = 0;
var doDebugging = (debugLevel) ? true : false;

/**
 * DEBUG HELPER.
 * @param string Message to debug
 */
function _debug(level, msg) {
    if (doDebugging && level >= debugLevel) {
        if (typeof window.console != 'undefined') {
            console.log(msg);
        } else {
            var e = document.getElementById('onlive_debug');
            if (!e) {
                e = document.createElement('DIV');
                e.setAttribute('id', 'onlive_debug');
                e.style.display = 'block';
                e.style.color = '#000';
                e.style.width = '100%';
                e.style.height = '100px';
                e.style.overflow = 'auto';
                e.style.position = 'absolute';
                e.style.bottom = '0';
                e.style.left = '0';
                e.style.background = '#f7f7f7';
                e.style.borderTop = '1px solid #000';
                e.style.padding = '10px';
                e.style.fontSize = '11px';
                e.style.lineHeight = '15px';
                e.style.textAlign = 'left';
                document.body.appendChild(e);
            }
            e.style.display = 'block';

            var l = document.createElement('p');
            l.style.padding = 0;
            l.style.margin = 0;
            l.innerHTML = msg;
            e.appendChild(l);
            e.scrollTop = e.scrollHeight;
        }
    }
}
 
/**
 * Extending Jquery password strength class
 */
$.fn.passwordStrength = function( options ){
	return this.each(function(){
		var that = this;that.opts = {};
		that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);

		that.div = $(that.opts.targetDiv);
		that.defaultClass = that.div.attr('class');

		that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;

		v = $(this)
		.keyup(function(){
			if( typeof el == "undefined" )
			this.el = $(this);
			var s = getPasswordStrength (this.value);
			if(this.value.length > 0) {
				var p = this.percents;
				var t = Math.floor( s / p );
	
				if( 100 <= s )
				t = this.opts.classes.length - 1;
	
				this.div
				.removeAttr('class')
				.addClass( this.defaultClass )
				.addClass( this.opts.classes[ t ] );
			}
			else{
				this.div
				.removeAttr('class')
				.addClass( this.defaultClass );
			}
		})
		
	});

	function getPasswordStrength(H){
		var D=(H.length);
        var E=0;
        if (D) {
            var num = (/[0-9]/m.test(H)) ? 1 : 0;
            var small = (/[a-z]/m.test(H)) ? 1 : 0;
            var big = (/[A-Z]/m.test(H)) ? 1 : 0;
            var special = (/[!@#$%^&*()_+\-={}\]\[\|":;,<.>?`~']/m.test(H)) ? 1 : 0;
            var types = parseInt(num) + parseInt(small) + parseInt(big) + parseInt(special);
            if (D < 8) {
                if(types==1){E=0}else{E=5}
            } else {
                if(types==1){E=0}else if(types==2){E=5}else if((types==3) || (types==4)){E=10}
            }
		}
		var F=E*10;
		if(F<0){F=0}
		if(F>100){F=100}
		return F
	}
};

function handlePromoForm()
{
		$("#register_promo_form").validate({
			rules: {
				registration_code: {
					required: true
				}
			},
			messages: {
				registration_code: {
					required: 'Registration code is required.'
				}
			},
            errorElement: "div"
		});	
}

/**
 * Reactivate Functions
 */
function handleReactivateForm() {
    
    if($("form#reactivate_subscription_form").length > 0) {
        reactivateValidatorObj = $("form#reactivate_subscription_form").validate({
            errorElement: "div",
                rules: {
                    activate_check:{
                        required:true
                    }
                },
                messages:{
                    activate_check:{
                        required:'Please select this box to continue.'
                    }
                }
        });
    }
}

/**
 * Suspension Functions
 */
function handleSuspendForm()
{
    
    $('#cancellationReason').change(function() {
        if ($('#cancellationReason').val() == 'other'){
            $("#divotherReason").show().removeClass("d_none");
        }
        else {
            $("#divotherReason").hide().addClass("d_none");
        }
    });
    
    if($("form#suspend_subscription_form").length > 0) {
        suspendValidatorObj = $("form#suspend_subscription_form").validate({
    		errorElement: "div",
    	  	rules: {
      	 		suspend_check:{
    			    required:true
    			},
    			reason: {
			        checkreason:true
    			},                
                other_reason: {
                    checkotherreason:true
                },
                comments: {
                    required: true
                }
    		},
    	  	messages:{
    		  	suspend_check:{
    			    required:'Please select this box to continue.'
			    },
		  	    reason:{
  			        checkreason:'Please select a reason.'
  			    },                
                other_reason: {
                    checkotherreason:'Please provide your reasoning.'
                },
                comments: {
                    required:'Please provide a description.'
                }
		    }
        });
    }
}

/**
 * Edit Shipping Method for Web Store
 */
function handleEditShippingMethod()
{   
    if($("form#edit_shipping_method").length > 0) {
        editshipValidatorObj = $("form#edit_shipping_method").validate({
            errorElement: "div",
            rules: {
                shipping_method:{
                    required:true
                }
            },
            messages:{
                shipping_method:{
                    required:'Please select a shipping method.'
                }
            }
        });
    }
}

function suspendNext()
{
    $('#suspend_page1').hide().addClass('d_none');
    $('#suspend_page2').show().removeClass('d_none');
}

var minTimeout = 1000;
var maxTimeout = 10000;
var multiplier = 2;
var prevContent = '';

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function jqueryExtendedFunctions()
{
	jQuery.fn.extend({
		wrapText: function(word_max_length){
			return $(this).html(wordwrap($(this).text(), word_max_length));
	  	}
	});
}

function wordwrap(text, word_max_length)
{
	var user_agent = navigator.appVersion.replace(/\s/g,'');
	var aText = text.split(' ');
	for(var i=0; i < aText.length; i++) {
		if(aText[i].length > word_max_length) {
			var aTmpTxt = aText[i].match(RegExp('.{1,'+word_max_length+'}','g'));
			if(/MSIE8.0/.test(user_agent)) {
				aText[i] = aTmpTxt.join('&#8203;');	
			} else {
				aText[i] = aTmpTxt.join('<wbr>');
			}
		}
	}
	return aText.join(' ');	
}

function daysInFebruary (year)
{	
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
/*
jQuery.validator.addMethod("notEqualTo", function(value, element, param){
        if($(param).val()==value){return false}else{return true}
},"Can't be same as old one!");

//checks non white space 7 bit ascii chars 
jQuery.validator.addMethod("prohibittedchars", function(value, element){
	if ((!value) || /^[\x21-\x7E]+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Prohibitted characters!");

//checks 7 bit ascii chars
jQuery.validator.addMethod("checknonascii", function(value, element){
	if(value) {
		return (/^[\x20-\x7E]+$/.test(value)) && (!((/&(#)?[a-zA-Z0-9]*;/.test(value)) ||
           value.match(/<(\/)?script\b[^>]*>/)));
	} else {
		return true;
	}
},"Prohibitted characters!");

jQuery.validator.addMethod("checktitle", function(value, element){
	if (value == element.title) {
		return false;
	} else {
		return true;
	}
},"Oops! Invalid.");

jQuery.validator.addMethod("checkzip", function(value, element){
	if (/^[0-9]{5}$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Invalid Zip Code.");

jQuery.validator.addMethod("checkstate", function(value, element){
	if (/^[A-Za-z]{2}$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Please provide state");

jQuery.validator.addMethod("checknumtitle", function(value, element){
	if(value) {		
		if (value == element.title) {
			return true;
		} else {
			var patt=/^[0-9]+$/;
			if (patt.test(value)) {
				return true;
			} else {
				return false;
			}
		}
	} else {
		return true;
	}
},"Oops! Invalid.");

jQuery.validator.addMethod("checkchars", function(value, element){
					
	if (/^[A-Za-z]+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Invalid");

jQuery.validator.addMethod("checkTagChars", function(value, element){
    // var newVal = value.replace(/[\s]{2,}/g,' ')
    //               .replace(/[\-]{2,}/g,'-')
    //               .replace(/[\_]{2,}/g,'_');
    element.value = $.trim(value);
    if (/^([A-Za-z0-9\_\-\s'])+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Player Tag may only contain non-international letters, numbers, spaces, underscores and dashes.");

jQuery.validator.addMethod("checkMottoChars", function(value, element){
	if (/^([A-Za-z0-9\s!._?,:'"\-])+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Unsupported characters!");

jQuery.validator.addMethod("checkQAChars", function(value, element, params){
	if(params == 'Q') {
		if (/^([A-Za-z0-9\s\?])+$/.test(value)) {
		  return true;
		}
	} else {
	  if (/^([A-Za-z0-9\s])+$/.test(value)) {
		  return true;
		}
	}
	return false;
},"Unsupported characters!");

jQuery.validator.addMethod("cardexpiry", function(value, element){
		
		var expirymonth=$('#expiryMonth').val();
		var expiryyear=$('#expiryYear').val();	
		if (expirymonth != '' && expiryyear != '' && 
				!isNaN(expirymonth) && !isNaN(expiryyear)){	
						
			daysarr=DaysArray(12);
			expirydate=daysarr[expirymonth];
			if (expirymonth==2) {
				expirydate=daysInFebruary(expiryyear);
			}
			var sdate=new Date();
			//selected date
			sdate.setDate(expirydate);
			sdate.setMonth(expirymonth-1);
			sdate.setFullYear(expiryyear);
			var stime=sdate.getTime();
			//present date
			var pdate=new Date();
			var ptime=pdate.getTime()
			if (ptime > stime) {
				return false;
			} else {				
				$('#expiryYear.error_msg').removeClass('error_msg');
				return true;
			}			
		} else {
			return true;
		}
},"Please provide valid expiration date");

jQuery.validator.addMethod("checkcvv", function(value, element){
    var thisval = $.trim(value);
    var ccnum = $.trim($('#cardNum').val());
	if(/^[\*]{3,4}$/.test(thisval) && /^[\*]+[0-9]{4}$/.test(ccnum))
	return true;
	if(thisval && /^[0-9]{3,4}$/.test(thisval)) {
  	    switch($('#creditCardType').val()){
  	    	case 'AmericanExpress':
  	    		if(thisval.length==4)
  	    			return true;
  	    		else
  	    			return false;
  	    		break;
  	    	default:
  	    		if(thisval.length==3)
  	    		    return true;
  	    	    else
  	    		    return false;
  	    }
	} else {
		return false;
	}
},"Security code is invalid.");

jQuery.validator.addMethod("restrictInput", function(value, element, params){
		if (value.length > params) {
			element.value = value.substr(0,params);
		}
        return true;
},"Oops! Maximum limit:{0} reached.");

jQuery.validator.addMethod("emailExtended", function(value, element){
   var parts = value.split(".");
   //return /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i.test(value);
   var domainName = parts[parts.length - 1];
   return /^([A-Z0-9_%+-]+([\+_.\-]?[A-Z0-9_%+-]+)*@[A-Z0-9]+[A-Z0-9.-]*)/i.test(value)
   		  && /^[A-Z]{2,4}$/i.test(domainName);
},"Please enter a valid email address");

jQuery.validator.addMethod("checkcreditcard", function(value, element, params){
  var CCNumber = value.replace(/\s|\-/g,'');
    return  $.validator.methods.creditcard.call(this, CCNumber, element) && 
            CCNumber.length < 17 && CCNumber.length > 12 && /[0-9]$/i.test(CCNumber);
},"Invalid card number");

jQuery.validator.addMethod("phoneNumber", function(value, element){
	
	var phoneNumber = value.match(/\d+/g);
	if (phoneNumber) {
		phoneNumber = phoneNumber.join('');
		if (/^[0-9]{10}$/.test(phoneNumber)) {
			return true;
		} else {
			return false;
		}
	}
	
  
},"Invalid phone number");

jQuery.validator.addMethod("recaptchaResponse", function(value, element){
 var login_count = getCookie('login_count'); 
 if(recaptcha_public_key && login_count && login_count >= 5) {
     if(value){
         return true;
     } else {
         return false;
     }
 } else {
     return true;
 }
   
}, "Enter the words you see in the box");

jQuery.validator.addMethod("checkreason", function(value, element){
	if (/^[A-Za-z]+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Please provide a reason");

jQuery.validator.addMethod("checkotherreason", function(value, element){
    if ($('#cancellationReason').val() == 'other'){
        if (/^([\s\S]){1,45}([\s\.])/.test(value)) {
     	    return true;
     	} else {
     	  return false;
     	}   
        
    }
    return true;

},"Please provide a reason");
*/
function getCCDisplay(CCNumber)
{
	CCNumber = String(CCNumber);
	if (CCNumber.length == 16) {
    	CCNumber = '************'+CCNumber.slice(12);
    } else if (CCNumber.length == 15) {
    	CCNumber = '***********'+CCNumber.slice(11);
    } else if (CCNumber.length == 14) {
    	CCNumber = '**********'+CCNumber.slice(10);
    } else {
    	CCNumber = '';
    }
    return CCNumber;
}

function getPhoneDisplay(mobile)
{
	var mobile= String(mobile);
	if (mobile.length == 10) {
    	  var format = '('+mobile.slice(0,3)+')'+' '+mobile.slice(3,6)+'-'+mobile.slice(6);
          return format;
    } 
    return mobile;
}

function checkCookieEnabled()
{
	var cookieEnabled=(navigator.cookieEnabled)? true : false
	//if not IE4+ nor NS6+
	if(typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
	document.cookie="testcookie"
	cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
	}
	return cookieEnabled;
}

function fieldLength(element, length, e)
{	
    charLength = element.value.length - element.value.replace(/\s/g,'').replace(/\-/g,'').length; 
    if( typeof e != "undefined" ) {
        if (e.keyCode) kCode = e.keyCode;
        else if (e.which) kCode = e.which;
        
        if (!((kCode == 32) ||(kCode == 37) || (kCode == 39))) {
            element.value = element.value.substr(0, length+charLength);
        }
    } else {
    element.value = element.value.substr(0, length+charLength);
    }
}

function showTextCounter(element, counterID, maxLen) {   
    if (element.value.length > maxLen){
        element.value = element.value.substring(0, maxLen);
    }
    var showText = element.value.length + "/" + maxLen;
    $("#"+counterID).html(showText);
}

function removeSpecials(e)
{ 
    var keycode = e.keyCode | e.which;
    var key_code = e.charCode? e.charCode : keycode;
    allowedKeys = new Array(8,9,13,17,18,27,32,33,34,35,36,37,38,39,40,45,46,109,116,123,189,224);
    if (!((findIndexOfArray(key_code, allowedKeys)+1) || (key_code > 47 && key_code < 58) ||
                      (key_code > 95 && key_code < 106))) {
        var oElement = window.event ? window.event.srcElement : e ? e.target : null;   
            if (/[^\d\s\-]/.test(oElement.value))
            oElement.value = oElement.value.replace(/[^\d\s\-]/g, '');
    }
}

function maskPhoneNumber(e)
{
	 var keycode = e.keyCode | e.which;
   	 var key_code = e.charCode? e.charCode : keycode;		
	 var phone = this.value.replace(/[^0-9]+/g, '');
	 notAllowedKeys = new Array(35, 36, 37, 38, 39, 40, 45, 46);
	 if( phone.length > 0 && !(findIndexOfArray(key_code, notAllowedKeys)+1) )
     {
        if(siteRegion == "UK"){
            if (phone.length == 11) {
                phone = phone.substr(0,5) + '-' + phone.substr(5,6);
            }
        }else{
            if (phone.length == 12) {
                phone = phone.substr(0,2) + '-' + phone.substr(2,3) + '-' + phone.substr(5,3) + '-' + phone.substr(8,4);
            } else if (phone.length == 11) {
                phone = phone.substr(0,1) + '-' + phone.substr(1,3) + '-' + phone.substr(4,3) + '-' + phone.substr(7,4);
            } else if (phone.length == 10) {
                phone = phone.substr(0,3) + '-' + phone.substr(3,3) + '-' + phone.substr(6,4);
            }
        }
	 	this.value = phone;
	 } else if(phone.length == 0) {
		this.value = '';
	 }
}

function maskZipNumber(e)
{
    var zip = this.value.replace(/[^0-9a-zA-Z\-\s]+/g, '');
    if (zip.length > 3) {
        this.value = zip;
    } else if(zip.length == 0) {
        this.value = '';
    }
}

function findIndexOfArray(elem, list)
{
    for(var i=0; i<list.length; i++){
        if(list[i]==elem){
         return i;
        }
    }
    return -1;
}

function handleSelection(d)
{
    if (document.selection) {
        sel = document.selection.createRange();
        if(sel.text){return true;}else{return false;}
    } else {
        if (d.selectionStart || d.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = d.selectionStart;
            endPos = d.selectionEnd;
            if (startPos != endPos) {return true;} else {return false;}
        } else {return false;}
    }
}

function maskCvvInput(e)
{
    var keycode = e.keyCode | e.which;
    var key_code = e.charCode? e.charCode : keycode;
    var oElement = window.event ? window.event.srcElement : e ? e.target : null;
    allowedKeys = new Array(8,9,13,27,33,34,35,36,37,38,39,40,45,46,116,123,224);
    
    if (!e.shiftKey && !e.ctrlKey && !e.altKey) {
            if ((key_code > 47 && key_code < 58) ||
                      (key_code > 95 && key_code < 106)) {
                          if (key_code > 95) {key_code -= (95-47);}
                            
                          if (oElement.value.length < 4) {
                            return true; }
                          else {
                            return handleSelection(this);
                          }
            } else if (findIndexOfArray(key_code, allowedKeys)+1) {
                return true;
            }  else { return false; }
    }
    return true;
}

function getUrlVars (urlstring, name) {
    var vars = [], hash;
    var hashes = urlstring.slice(urlstring.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    if (name) {
        return vars[name];
    } else {
        return vars;
    }
}

jQuery.fn.extend({
    center: function (width) {
        this.css('width', null);
        var shapewidth = (width == undefined) ? this.width() : width;
        var leftoffset = ( $(window).width() - shapewidth ) / 2+$(window).scrollLeft();
        // console.log(shapewidth);
        // console.log(leftoffset);
        this.css("position","absolute");
        this.css("left", leftoffset + "px");
        this.css('width', shapewidth + 'px');
        return this;
    }
});

// Get a variable's value in the query string.
function getQueryVariable(variable) { 
    // alert('checking stuff');
    var query = document.location.hash.substring(1);
    if (query.length < 1) {return null}
    var vars = query.split("&"); 
    for (var i=0;i<vars.length;i++) { 
        var pair = vars[i].split("="); 
        if (pair[0] == variable) { 
            // console.log('GETING '+pair[0]+' = '+pair[1]);
            return pair[1]; 
        }
    }
    return null;
}



function encode64(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    var keyStr = "ABCDEFGHIJKLMNOP" +
                  "QRSTUVWXYZabcdef" +
                  "ghijklmnopqrstuv" +
                  "wxyz0123456789+/" +
                  "=";

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
        keyStr.charAt(enc1) +
        keyStr.charAt(enc2) +
        keyStr.charAt(enc3) +
        keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
}

/* TODO change casing switches to be more intuitive. eg, P = AM/PM, p = am/pm */
function formatDate(date,format) {
    // %M minutes with leading zeros
    // %I 12-hour format of an hour with leading zeros
    // %p AM or PM.
    // %P am or pm.
    // %d day of the month with leading zeros
    // %D day of the month without leading zeros
    // %m month without leading zeros 
    // %ma month name as month abbreviation
    // %Y year including century   

    var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]; 

    var dateinfo = new Array(); 
    var min = date.getMinutes();
    dateinfo['%M'] = (min < 10) ? ("0" + min) : min;
    var hour = (date.getHours() % 12 == 0) ? 12 : (date.getHours() % 12); 
    dateinfo['%i'] = hour;
    dateinfo['%I'] = (hour < 10) ? ("0" + hour) : hour;
    dateinfo['%p'] = (date.getHours() < 12) ? 'AM': 'PM';
    dateinfo['%P'] = (date.getHours() < 12) ? 'am': 'pm';
    var day = date.getDate();
    dateinfo['%d'] = (day < 10) ? ("0" + day) : day;
    dateinfo['%D'] = day;
    dateinfo['%ma'] = months[date.getMonth()];
    dateinfo['%m'] = date.getMonth() + 1;
    dateinfo['%Y'] = date.getFullYear();
    for (var d in dateinfo) {
        format = format.replace(d, dateinfo[d]);
    }
    return format;
}



