$(document).ready(function(){
   
    $("#ajax_loading").ajaxStart(function(){
        $(this).show();        
    });
    $("#ajax_loading").ajaxStop(function(){
        $(this).hide();        
    });

    var showmessagearr = new Array(2);
    function showmessage(h, u, m) {
        $.ajax({
            async: false,
            type: "POST",
            url: "../ajax/game.php",
            data: {
                func: "checkMessage",
                u: u,
                m: m
            },
            success: function(ret) {
                var show = ar(ret);
                showmessage[u+' '+m] = ret;
            }
        });
        
        if (show != true) {
            return;
        }
        $("#dialog_box").html(h);
        $("#dialog_box").show(1);
        $("#dialog_box").dialog({ 
            modal: true, 
            dialogClass: "flora",
            overlay: { 
                opacity: 0.6, 
                background: "black" 
            },
            buttons: { 
                "Okay": function() { 
                    $(this).dialog("close"); 
                }, 
                "Don't show again": function() { 
                    $.ajax({
                        async: false,
                        type: "POST",
                        url: "../ajax/game.php",
                        data: {
                            func: "hideMessage",
                            u: u,
                            m: m
                        },
                        success: function(ret) {
                            $(this).dialog("close"); 
                        },
                        error: function(ret) {
                            alert (ret);
                        } 
                    });                 
                } 
            } 
        });
    }           
});

//ajax return handler
function ar(x) {
    var errors = x.match(/\{\{\{.*?\}\}\}/g);
    var log = x.match(/\[\[\[.*?\]\]\]/g);
    
    for (e in errors) {  
       console.error(str_replace('{{{', '', str_replace('}}}', '', errors[e])));
       x = str_replace(errors[e], "", x);
    }  
    for (e in log) {  
       console.info(str_replace('[[[', '', str_replace(']]]', '', log[e])));
       x = str_replace(log[e], "", x);
    }
    
    return x;    
} 

function showmessage(h, u, m) {
    var show;
    $.ajax({
        async: false,
        type: "POST",
        url: "../ajax/game.php",
        data: {
            func: "checkMessage",
            u: u,
            m: m
        },
        success: function(ret) {
            show = ret;
        },
        error: function(ret) {
            alert (ret);
        } 
    });
    if (show == 0) {
        return;
    }
    $("#dialog_box").html(h);
    $("#dialog_box").show(1);
    $("#dialog_box").dialog({ 
        modal: true, 
        dialogClass: "flora",
        overlay: { 
            opacity: 0.6, 
            background: "black" 
        },
        buttons: { 
            "Okay": function() { 
                $(this).dialog("close"); 
            }, 
            "Don't show again": function() { 
                $.ajax({
                    async: false,
                    type: "POST",
                    url: "../ajax/game.php",
                    data: {
                        func: "hideMessage",
                        u: u,
                        m: m
                    },
                    error: function(ret) {
                        alert (ret);
                    } 
                });
                $(this).dialog("close");                
            } 
        } 
    });
}   

function explode( delimiter, string, limit ) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     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;
    }
}

var STR_PAD_LEFT = 1;
var STR_PAD_RIGHT = 2;
var STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {

    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = STR_PAD_LEFT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case STR_PAD_BOTH:
                var right = Math.ceil((padlen = len - str.length) / 2);
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;

}

function strstr( haystack, needle, bool ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strstr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
 
    var pos = 0;
 
    haystack += '';
    pos = haystack.indexOf( needle );
    if( pos == -1 ){
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
 
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
        }
    };
 
    return sa ? s : s[0];
}

jQuery.fn.delay = function(time,func){
    this.each(function(){
        setTimeout(func,time);
    });
    
    return this;
};

function pow(image, x, y) {
	if (x == 0) {
		x=Math.floor(Math.random()*500);
	}
	if (y == 0) {
		y=Math.floor(Math.random()*300);
	}
	$(".pow").css({"top":y+"px", "left":x+"px", "background-image":"url(../images/icons/pow/"+image+".png"});
	$(".pow").fadeIn(100).animate({"top":"-=25"}, 400, function() {
		$(".pow").animate({"top":"-=25", "opacity":"1"}, 400);
	});
}

function powlist (text) {
	//split it all up
	var chunks = text.split(":");
	var coords = chunks[0].split("x");
	var x = coords[0];
	var y = coords[1];
	var powlist = chunks[1].split("|");
	for (var i in powlist) {
		pow(powlist[i], x, y);
		sleep(1000);
	}
}

function sleep(delay) {
	var start = new Date().getTime();
	while (new Date().getTime() < start + delay);
}

function testPassword(passwd)
{
		var intScore   = 0
		var strVerdict = "weak"
		
		// PASSWORD LENGTH
		if (passwd.length<5)                         // length 4 or less
		{
			intScore = (intScore+3)
		}
		else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
		{
			intScore = (intScore+6)
		}
		else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
		{
			intScore = (intScore+12)
		}
		else if (passwd.length>15)                    // length 16 or more
		{
			intScore = (intScore+18)
		}
		
		
		// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
		if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
		{
			intScore = (intScore+1)
		}
		
		if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
		{
			intScore = (intScore+5)
		}
		
		// NUMBERS
		if (passwd.match(/\d+/))                                 // [verified] at least one number
		{
			intScore = (intScore+5)
		}
		
		if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
		{
			intScore = (intScore+5)
		}
		
		
		// SPECIAL CHAR
		if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
		{
			intScore = (intScore+5)
		}
		
									 // [verified] at least two special characters
		if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
		{
			intScore = (intScore+5)
		}
	
		
		// COMBOS
		if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        // [verified] both upper and lower case
		{
			intScore = (intScore+2)
		}

		if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
		{
			intScore = (intScore+2)
		}
 
									// [verified] letters, numbers, and special characters
		if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
		{
			intScore = (intScore+2)
		}
	
	return intScore;	
}

