/*
 * @title: mtg-common.js
 * @author: Benjamin Neil
 * @desc: used to facilitate the mtg tech stack  
 */
var MTG = {
    CONSTANTS: {
        debug: true,
        comp_location: "/playnow/"
    },
    errCodes: {
        codes: [{
            "uramCode": "password1",
            "code": "PASSWORD_REQUIRED",
            "desc": "Please enter a Password.",
            "field": "stationConfirmPassword"
        },
        {
            "uramCode": "dobYear",
            "code": "DOB_YEAR_INVALID_MUST_BE_GREATER_THAN_1900_AND_LESS_THAN_2500",
            "desc": "Please enter a valid Year of Birth.",
            "field": "year"
        },
        {
            "uramCode": "tosAccepted",
            "code": "TOS_REQUIRED",
            "desc": "Please indicate that you have read and accept the <a style=\"color:##FFBA00\" target=\"_blank\" href=\"http://www.station.sony.com/en/termsofservice.vm\" style=\"color:##FFBA00\">Terms of Service<\/a> before continuing.",
            "field": "agreeEula"
        },
        {
            "uramCode": "emailAddress",
            "code": "EMAIL_REQUIRED",
            "desc": "Please enter your E-mail Address.",
            "field": "email"
        },
        {
            "uramCode": "dobDay",
            "code": "DOB_DAY_INVALID_MUST_BE_BETWEEN_1_AND_31",
            "desc": "Please enter a valid Day of Birth.",
            "field": "day"
        },
        {
            "uramCode": "stationName",
            "code": "STATION_NAME_REQUIRED",
            "desc": "Please choose a Station Username.",
            "field": "stationUsername"
        },
        {
            "uramCode": "privacyPolicyAccepted",
            "code": "PRIVACY_POLICY_REQUIRED",
            "desc": "Please indicate that you have read and accept the <a target=\"_blank\" href=\"http://www.station.sony.com/sonyonline/privacy.vm\">Privacy Policy<\/a> before continuing.",
            "field": "agreeEula"
        },
        {
            "uramCode": "dobMonth",
            "code": "DOB_MONTH_INVALID_MUST_BE_BETWEEN_1_AND_12",
            "desc": "Please enter a valid Month of Birth.",
            "field": "month"
        },
        {
            "uramCode": "country",
            "code": "COUNTRY_REQUIRED",
            "desc": "Please enter your Country of residence.",
            "field": "country"
        }]
    },
    utils: {
        log: function (txt) {
            if (window.console && MTG.CONSTANTS.debug) {
                window.console.log.apply(window.console, arguments);
            }
        },
        cookies: {
            //example usage
            //setCookie( 'sample', true, 14, '/', '', '' );
            setCookie: function (name, value, expires, path, domain, secure) {
                var today = new Date();
                today.setTime(today.getTime());

                if (expires) {
                    expires = expires * 1000 * 60 * 60 * 24;
                }
                var expires_date = new Date(today.getTime() + (expires));

                document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
            },

            getCookie: function (check_name) {
                var a_all_cookies = document.cookie.split(';'),
                    a_temp_cookie = '',
                    cookie_name = '',
                    cookie_value = '',
                    b_cookie_found = false;

                for (i = 0; i < a_all_cookies.length; i++) {
                    a_temp_cookie = a_all_cookies[i].split('=');
                    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
                    if (cookie_name == check_name) {
                        b_cookie_found = true;
                        if (a_temp_cookie.length > 1) {
                            cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                        }
                        // note that in cases where cookie is initialized but no value, null is returned
                        return cookie_value;
                        break;
                    }
                    a_temp_cookie = null;
                    cookie_name = '';
                }
                if (!b_cookie_found) {
                    return false;
                }
            },

            deleteCookie: function (name, path, domain) {
                if (FBH.cookies.getCookie(name)) {
                    document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
                }
            }
        },

        returnErrorCode: function (str) {
            var i = 0;

            for (i = 0; i < MTG.errCodes.codes.length; i++) {
                if (str === MTG.errCodes.codes[i].uramCode) {
                    return MTG.errCodes.codes[i].desc;
                }
            }
            MTG.utils.log("problem finding error code, problem string: " + str);
            return false;
        },

        output: function (str, outDiv) {
            $('#' + outDiv).html(str);
            return false;
        },

        ajax: function (url, callback, params) {
            if (params === null) {
                params = "";
            } else {
                params = "?" + params;
            }
            var target = url + params;
            MTG.utils.log(target);
            $.ajax({
                type: 'POST',
                url: target,
                success: function (json) {
                    callback(json);
                },
                error: function (err) {
                    MTG.utils.log(err);
                },
                dataType: 'json'
            });
        }

    },
    VALIDATION: {

        events: {
            checkStationUsername: function () {
                var stationName = $("#stationUsername").val();
                MTG.utils.ajax(MTG.CONSTANTS.comp_location + "checkname.vm", MTG.VALIDATION.events.onCheckNameComplete, "value=" + stationName);
            },

            onCheckNameComplete: function (data) {
                var i = 0,
                    str = "";
                MTG.utils.log("data valid?:" + data.valid);
                if (data.valid) {
                    return true;
                } else {
                    for (i = 0; i < data.suggestedStationNames.length; i++) {
                        str += '<a style="color:#FFEA00" href="javascript:void(0);" onclick="changeUserName(\'' + data.suggestedStationNames[i] + '\')" >' + data.suggestedStationNames[i] + "</a> ";
                    }
                    $.validationEngine.buildPrompt($("#stationUsername"), "Station Username is already in use, how about:\r\n" + str, "error");
                    return false;
                }
            },

            onValidationComplete: function (data, caller) {
                var i = 0,
                    j = 0,
                    obj = null;
                MTG.utils.log("total errors on validation complete: " + data.errors.length);
                if (data.errors.length === 0) { // success
                    window.location = MTG.CONSTANTS.launcherURL;
                } else {
                	// errors
                    if (data.fieldErrors.password1 !== undefined) {
                        obj = $("#stationConfirmPassword");
                        desc = MTG.utils.returnErrorCode("password1");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.dobYear !== undefined) {
                        obj = $("#year");
                        desc = MTG.utils.returnErrorCode("dobYear");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.tosAccepted !== undefined) {
                        obj = $("#agreeEula");
                        desc = MTG.utils.returnErrorCode("tosAccepted");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.emailAddress !== undefined) {
                        obj = $("#email");
                        desc = MTG.utils.returnErrorCode("emailAddress");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.dobDay !== undefined) {
                        obj = $("#day");
                        desc = MTG.utils.returnErrorCode("dobDay");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.stationName !== undefined) {
                        obj = $("#stationUsername");
                        desc = MTG.utils.returnErrorCode("stationName");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.privacyPolicyAccepted !== undefined) {
                        obj = $("#agreeEula");
                        desc = MTG.utils.returnErrorCode("privacyPolicyAccepted");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.dobMonth !== undefined) {
                        obj = $("#month");
                        desc = MTG.utils.returnErrorCode("dobMonth");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    if (data.fieldErrors.country !== undefined) {
                        obj = $("#country");
                        desc = MTG.utils.returnErrorCode("country");
                        $.validationEngine.buildPrompt(obj, desc, "error");
                    }
                    return false;
                }
            }
        },
        
		startDownload : function(cid){
					params = {
						"digestFolder" : "Magic The Gathering Tactics",
						"digest" : "http://launch.soe.com/game/magic/patch/bootstrap.soe",
						"cid" : cid,
						"launchArgs" : "queryString=campaignID="+cid
					}
					WebInstaller.instance(params.digestFolder, {
						src: params.digest,
						launchArgs: params.launchArgs,
						onInit:function(){
							if(window.location.hash.length > 0){
								window.location.hash = '';
							}
						},
						onPluginInstallInit: function () {
							window.location.hash=cid
						}
					}).addToPage().launch();
		},
		
		handleRefreshHash : function(){
            if (window.location.hash.length>1) {
                var hash = window.location.hash.substr(1);
                ids = hash.split(',');
                window.location.hash = '';
                if (ids.length>0) {
                    cid = ids[0];
                    env = ids[1];
                    if (cid>0) {
                        MTG.VALIDATION.startDownload(cid);
                    }
                }
            }
		
		}
    }
};

/*
 * mtg-common
 * misc common functions
 */
function validate2fields(){
	if ($("#stationPassword").val() !== $("#stationConfirmPassword").val()) {
		return false;
	}
	else {
		return true;
	}
}

function hasNumbers(){
	var regex = /\d/,
		t = $("#stationPassword").val(),
		test = regex.test(t);
	
	MTG.utils.log(test);
	return test;
}

function validateStationName(){
	MTG.utils.log("validating station name");
	if ($("#stationUsername").val() !== "") {
		MTG.VALIDATION.events.checkStationUsername();
	}
}

function changeUserName(name){
	$("#stationUsername").val(name);
}

function log(msg){
	MTG.utils.log(msg);
}
