if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}


// ============================ Container variable ============================ //
// let's try hard not to pollute the global object - makes debugging *Much* easier
// we'll put everything in a uWin
var redirectionObject;

var uWinAccount = {
    config: {
        api_url: "/_api-scripts/www/RPC-JSON/"
    },
    debug: function () {
        /*if ("undefined" !== typeof(console)) {
            if ("undefined" !== typeof(console.log)) {
                //console.log.apply(console, arguments);
            }
        }*/
    },
    objects: {},
    test: {}
};

// contains:
//	objects: {},
//	state: {},
//	api: {},
//	ui: {},
//	site: {}
//	test: {}
// ============================ Utilities ============================ //
// provides a shortcut to inheritance - makes 'this' a subclass of 'parent'
Function.prototype.inherits = function (parent) {
    if ("function" === typeof(parent)) {
        this.prototype = new parent();
    }
    return this;
};

// allows you to bind a function to the specified scope - basically, let's you set what the 'this' of a function refers to
Function.prototype.bind = function (context) {
    var fn = this;
    return function () {
        return fn.apply(context, arguments);
    };
};

// cross browser Array.each - uses native (fast) Array.forEach if it exists (eg. FireFox, Safari, Chrome)
if ("function" === typeof([].forEach)) {
    Array.prototype.each = Array.prototype.forEach;
} else {
    Array.prototype.each = function (fn) {
        for (var i = 0, l = this.length; i < l; i++) {
            fn(this[i], i, this);
        }
    };
}

// cross browser Array.filter based on example on the MDC page
if (!Array.prototype.filter) {
    Array.prototype.filter = function (fn) {
        var res = [];
        for (var i = 0, l = this.length; i < l; i++) {
            var val = this[i];
            // in case fn mutates this
            if (fn.call(this, val, i, this)) {
                res.push(val);
            }
        }
        return res;
    };
}

// ============================ Core Object (superclass) ============================ //
uWinAccount.objects.uWin_OBJECT = function () {
    this.get = function (property) {
        return this[property];
    };
    this.set = function (property, value) {
        this[property] = value;
    };
    this.populate = function (data) {
        if (data) {
            for (var prop in this) {
                // don't set to undefined - we're using null as the 'empty' marker
                if ("undefined" !== typeof(data[prop]) && "_parent" !== prop) {
                    // do not want to filter with ownProperty because we're inheriting
                    this[prop] = data[prop];
                }
            }
        }
        return this;
    };
};

// ============================ Re-usable Objects ============================ //


// ============================ Communication layer ============================ //
uWinAccount.api = new

function ($) {
    /**
     *	AJAX request callbacks - metacallbacks, if you will
     */
    // fires whenever a request begins - designed for UI interactions (eg loading icons)
    var onRequest = function (service, method, data) {

    };
    // fires whenever a request ends - designed for UI interactions (eg loading icons)
    var onComplete = function (request) {

    };
    // fires when a callcompletes successfully - designed for handling the response
    var onSuccess = function (data, status, service, method) {
        uWinAccount.debug(".comms.onSuccess", arguments);
    };
    // fires when a request fails - designed for handling errors
    var onError = function (request, status, error, service, method) {
        uWinAccount.debug(".comms.onError", arguments);
    };

    // rpc insists on having the call id per-service
    var id = {
        Customer: 1,
        Betting: 1
    };
    /**
     *	Actually makes the request of the api
     *
     *
     *	@param service String - the servce name, eg Customer
     *	@param method String - the method name, eg Login
     *	@param paras Array - an array of parameters to pss to the API
     *	@param successCallback - a function to execute when the request completes succesfully (optional, but typically necessary)
     *	@param errorCallback - a function to execute if the request fails (optional, but typically necessary)
     *	
     */
    var makeCall = function (service, method, params, successCallback, errorCallback) {
        var data = {
            method: method,
            params: params,
            jsonrpc: "2.0",
            id: id[service]++
        };
        onRequest(service, method, params);
        $.ajax({
            url: uWinAccount.config.api_url + service + "/",

            cache: false,
            dataType: "json",
            data: JSON.stringify(data),
            type: "POST",

            complete: onComplete,
            error: function (request, status, error, service, method) {
                onError(request, status, error, service, method);
                if ("function" === typeof(errorCallback)) {
                    errorCallback(request, status, error);
                }
            },
            success: function (data, status) {
                var responseData = data.result;
                onSuccess(responseData, status, service, method);
                if ("function" === typeof(successCallback)) {
                    successCallback(responseData, status);
                }
            }

        });

    };

    var makeSyncCall = function (service, method, params, successCallback, errorCallback) {
        var data = {
            method: method,
            params: params,
            jsonrpc: "2.0",
            id: id[service]++
        };
        var responseData;

        onRequest(service, method, params);
        $.ajax({
            url: uWinAccount.config.api_url + service + "/",
            cache: false,
            dataType: "json",
            data: JSON.stringify(data),
            async: false,
            type: "POST",
            complete: onComplete,
            error: function (request, status, error, service, method) {
                onError(request, status, error, service, method);
                if ("function" === typeof(errorCallback)) {
                    errorCallback(request, status, error);
                }
            },
            success: function (data, status) {
                responseData = data.result;
                onSuccess(responseData, status, service, method);
                if ("function" === typeof(successCallback)) {
                    successCallback(responseData, status);
                }
            }
        });

        return responseData;
    };


    /*
	 *	API methods - each comprised of a public method, a private success callback and a private error callback
	 */

    /**
     *	EchoResponse
     *	A means of testing the service is up - should return the passed text
     */
    var echoSuccess = function (data, status) {
        // this ethod doesn't do anything but log the response
        uWinAccount.debug("API Echo success", data);
    };
    var echoError = function (request, status, error) {
        uWinAccount.debug("Echo call failed", request, status, error);
    };
    this.echo = function (service, message) {
        var params = [
        message];
        makeCall(service, "TexasEcho", params, echoSuccess, echoError);
    };

    this.GetBalances = function () {
        return makeSyncCall("Account", "GetBalances");
    };

    this.GetPaymentTransaction = function (id) {
    	var params = [id];
    	return makeSyncCall("Account", "GetPaymentTransaction", params);
    };
    
    this.GetPersonalDetails = function () {
    	return makeSyncCall("Customer", "GetPersonalDetails");
    };	

    this.RefreshUserSession = function () {
    	return makeCall("Netent", "RefreshUserSession");
    };	
    
    this.GetRBWRequest = function (par) {
    	var params = [ par ];
    	return makeSyncCall("Account", "GetRBWRequest", params);
    };	

    this.CreatePokerAccount = function (par) {
    	var params = [ par ];
    	return makeSyncCall("Customer", "CreatePokerAccount", params);
    };	

	this.GetSecretQuestions = function () {
		var lang = window.location.pathname.split('/')[1];
		if (lang == 'register-form') {
			if (window.location.host=='www.youwin.tv') {
				lang = 'de';
			}
			if (window.location.host=='www.youwin.com') {
				lang = 'en';
			}
		}
		var params = [ lang ];
		return makeSyncCall('Content', 'getSecretQuestions', params);
	}
    
    this.BeginPaymentTransaction = function (type, instruction, amount, password) {
    	var params = [
    	              type, 
    	              instruction, 
    	              amount,
    	              password
    	              ];
    	return makeSyncCall("Account", "BeginPaymentTransaction", params);
    };

	this.RegisterCard = function (details) {
		var params = [details];
		return makeSyncCall ("Account", "RegisterCard", params);
	};

	this.GetDepositSuccessData = function () {
		return makeSyncCall ("Account", "GetDepositSuccessData");
	};

	this.GetDepositFailureData = function () {
		return makeSyncCall ("Account", "GetDepositFailureData");
	};

	this.RegisterCardAndDeposit = function (details, register) {
		var params = [details, register];
		return makeSyncCall ("Account", "RegisterCardAndDeposit", params);
	};

	this.NetellerRegister = function (details) {
		var params = [details];
		return makeSyncCall ("Account", "NetellerRegister", params);
	};

    this.BeginPaymentTransactionWithSecurityCode = function (type, instruction, amount, code, password) {
    	var params = [
    	              type, 
    	              instruction, 
    	              amount,
    	              code,
    	              password
    	              ];
    	return makeSyncCall("Account", "BeginPaymentTransactionWithSecurityCode", params);
    };
    
	this.StoreMoneybookersDeposit = function (key, val) {
		var params = [
			key,
			val
			];
		return makeSyncCall("Content", "store", params);	
	};
	
	this.GetMoneybookersDeposit = function (key) {
		var params = [
			key
		];
		return makeSyncCall("Content","get", params);
	};
    
    this.GetActivePaymentInstruments = function (type) {
    	var params = [
    	              '',
    	              type
    	              ];
    	return makeSyncCall("Account", "GetActivePaymentInstruments", params);
    };
    
    this.GetPaymentInstrument = function (instrument) {
    	var params = [
    	              instrument
    	             ];
    	return makeSyncCall("Account", "GetPaymentInstrument", params);
    }	

    this.PngTransferFunds = function (account, amount, from, to) {
        var params = [
                      account,
                      amount,
                      from, 
                      to];
        
        return makeSyncCall("Account", "PngTransferFunds", params);
    };	

    /* Functions by Jaroslaw Salwa */
	this.isHistoryToBeGenerated=function(){
		var params={"key":"account_from_landing"};
		makeCall("Content","get",params,isHistoryToBeGeneratedSuccess_1,isHistoryToBeGeneratedError);
	}
	var isHistoryToBeGeneratedError = function(request, status, error){
		//error
	}
	var BetTypeTmp;
	var isHistoryToBeGeneratedSuccess_1=function(data,status){
		if(data!=false){
	BetTypeTmp=data;
	var params={"key":"account_from_landing_from"};
	makeCall("Content","get",params,isHistoryToBeGeneratedSuccess_2,isHistoryToBeGeneratedError);
	}
	}
	var isHistoryToBeGeneratedSuccess_2=function(data,status){
	FromDate = data;
	var params={"key":"account_from_landing_to"};
	makeCall("Content","get",params,isHistoryToBeGeneratedSuccess_3,isHistoryToBeGeneratedError);

	}
	var isHistoryToBeGeneratedSuccess_3=function(data,status){
	ToDate = data;
		uWinAccount.api.ViewUserHistoryGenerate(FromDate,ToDate,BetTypeTmp);
	params={"key":"account_from_landing_to"
	};
	makeCall("Content","delete",params,isHistoryToBeGeneratedDeleteSuccess,isHistoryToBeGeneratedError);
	params={"key":"account_from_landing_from"
	};
	makeCall("Content","delete",params,isHistoryToBeGeneratedDeleteSuccess,isHistoryToBeGeneratedError);
	params={"key":"account_from_landing"
	};
	makeCall("Content","delete",params,isHistoryToBeGeneratedDeleteSuccess,isHistoryToBeGeneratedError);
	}


	var isHistoryToBeGeneratedDeleteSuccess=function(data,response){
		//
	}
	this.accountLandindHistory=function(){
		var params={"key":"account_from_landing","value":$("input[name=bets]:checked").val()};
		makeCall("Content","store",params,accountLandindHistorySuccess_1,accountLandindHistoryError);
	}
	var accountLandindHistoryError = function(request, status, error){
		//error
	}
	var accountLandindHistorySuccess_1=function(data,status){
	  var from_month = parseInt($(".from_month").val());
	    if (from_month < 10) from_month = "0" + from_month;
	    var from_day = parseInt($(".from_day").val());
	    if (from_day < 10) from_day = "0" + from_day;
		var l_from = $(".from_year").val() + "-" + from_month + "-" + from_day + "T" + "00" + ":" + "00" + ":" + "00";


		var params={"key":"account_from_landing_from","value":l_from};
makeCall("Content","store",params,accountLandindHistorySuccess_2,accountLandindHistoryError);
	}

	var accountLandindHistorySuccess_2=function(data,status){
		var to_month = parseInt($(".to_month").val());
		if (to_month < 10) to_month = "0" + to_month;
		var to_day = parseInt($(".to_day").val());
		//to_day = to_day - 1; //finsoft return to_day + 1 so i make it to -1
		if (to_day < 10) to_day = "0" + to_day;

		var l_to = $(".to_year").val() + "-" + to_month + "-" + to_day + "T" + 23 + ":" + 59 + ":" + 59;
			var params={"key":"account_from_landing_to","value":l_to};
			
		makeCall("Content","store",params,accountLandindHistorySuccess_3,accountLandindHistoryError);
	}

	var accountLandindHistorySuccess_3=function(data,status){
	window.location.href=$(".transaction_send_link").html();
	}
    var days_to_expire = 7;
    var logged_in = 2;
    var register_link = "http://www.youwin.com/en/register-form";
register_link=$("#registration_link a").attr("href");
    /* Change password functions */
    //Success of Changing password

    
    var ChangePasswordSuccess = function (data, status) {
        //Error checking
        if (data.SetPasswordExtResult == false) {
            //Changing password failed (most often not logged in)
            $(".change_passwords_inputs").html("<strong>"+_("Error")+"</strong><br />" + data.errorMessage);
            return false;
        } else if (typeof(data.SetPasswordExtResult) != "object") {
            //There is neither error nor exception - successfully changed password
            $(".change_passwords_inputs").html("<p>"+_("Success! ")+"<br />"+_("You have successfully changed your password.")+"</p>");
        } else if (typeof(data.SetPasswordExtResult) == "object") { // }else if (typeof(data.SetPasswordExtResult.1010) == "object") {
            //Changing password failed - probably bad password (ErrorMessages from this object were not right while writing it so i assumed it is about password)
            old = $("#old_password");
            old.val("");
            old.focus();
            old.next("span").remove();
            if ($(".error_main").html() == null) $(".change_passwords_inputs").prepend("<span class='error_main'><strong>"+_("Incorrect old password")+"</strong><br />"+_("The old password you entered does not match our records. Please try again.")+"</span>");
            else $(".error_main").html("<strong>"+_("Incorrect old password")+"</strong><br />"+_("The old password you entered does not match our records. Please try again."));
        } else return 0;
    };
    //Callback failed
    var ChangePasswordError = function (request, status, error) {
        $(".change_passwords_inputs").prepend("<span class='error'>"+_("Internal database error.")+"<br />"+_("Please try again later.")+"</span>");
    };
    var showErrorChangePassword = function (obj, text) {
        //Simple error displaying function to be used while editing password fields
        password_span_tags_1 = "<span>";
        password_span_tags_2 = "</span>"
        obj.next("span").remove();
        obj.after(password_span_tags_1 + text + password_span_tags_2);
    };
    //Validation after pressing submit button
    this.ChangePassword = function (password1, old_password) {

        //validation suceeded
        var params = [
        password1.val(), old_password.val()];
        //Everything is all right so we can use function SetPasswordExt
        makeCall("Customer", "SetPasswordExt", params, ChangePasswordSuccess, ChangePasswordError);

    };
	this.trim=function(str, chars) {
		return ltrim(rtrim(str, chars), chars);
	}

	var ltrim = function(str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	}

	var rtrim = function(str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	}
    //Validation function (validation after pressing any key in input)
    this.CheckPassword = function (type, obj, length, id_other, messages_change_password) {
        //Removing any error
        $(obj).next("span").remove();
        //checking what field it is 
        if (type == 'new_2') {
            //Checking length and then Equality to the password1
            if ($(obj).val().length >= length) if ($(id_other).val() == $(obj).val()) $(obj).after("<span>OK</span>");
            else showErrorChangePassword($(obj), messages_change_password['password_nequal']);
            else showErrorChangePassword($(obj), messages_change_password['password2']);
        } else if (type == 'new') {
            //Checking length of new password1
            if ($(obj).val().length >= length) $(obj).after("<span>OK</span>");
            else showErrorChangePassword($(obj), messages_change_password['password1']);
            this.CheckPassword('new_2', $(id_other), length, "#" + $(obj).attr("id"), messages_change_password);
        } else if (type == 'old') {
            //Checking length of old password
            if ($(obj).val().length >= 1) $(obj).after("<span>OK</span>");
        }
    };
    /* End Change Password functions */

    /* Edit Details */
    //Edit details success function
    var EditDetailsSuccess = function (data, status) {
        //Error checking
        if (data.UpdatePersonalDetailsExtResult == null) {
            //No Exception - Editing succeeded
			var lang = 'en';

			if (document.cookie.length>0) {
				c_start=document.cookie.indexOf ("lang=");
				if (c_start!=-1) {
					c_start=c_start + 5;
					c_end=document.cookie.indexOf (";",c_start);
					if (c_end==-1) c_end=document.cookie.length;
					lang = unescape(document.cookie.substring(c_start,c_end));
			    }
			}
			lang = lang.toLowerCase();            
			var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
			var redeye = 'https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl='+url+'change-confirm&language='+lang+'&change_confirm=confirm';
			redeye+='&change_address1=%%'+$('#StreetAddress').val();
			redeye+='&change_city='+$('#City').val();
			redeye+='&change_county='+$('#CountyOrStateOrProvince').val();
			redeye+='&change_postcode='+$('#PostCode').val();
			redeye+='&change_tel='+$('#HomePhone').val();
			redeye+='&change_mob='+$('#MobilePhone').val();
			$("#edit-details").html("<p>"+_("Success!")+"<br />"+_("Your contact details have been updated.")+"</p>");
			$("#edit-details").append('<img src="'+redeye+'"/>');
        } else if (data.SetPasswordExtResult == false) {
            //Error - displaying its errorMessage
            //data.errorMessage;//error
        } else if (data.UpdatePersonalDetailsExtResult != undefined && data.UpdatePersonalDetailsExtResult.WCFApplicationException.Message != null && data.UpdatePersonalDetailsExtResult.WCFApplicationException.Message != undefined) {
            //data.UpdatePersonalDetailsExtResult.WCFApplicationException.Message;
            //error probably bad password
            return 0;
        }
    };

    //Edit details error(callback) function
    var EditDetailsError = function (request, status, error) {
        $("#edit-details").prepend("<span class='error'>"+_("Internal database error.")+"<br />"+_("Please try again later.")+"</span>");
    };

    //Simple function to fill in input fields with data
    var fill_in = function (id_input, data, is_html) {
        if (data != "" && data != null) {
            if (is_html == null) $("#" + id_input).val(data);
            else $("#" + id_input).html(data); //if thing which needs to be filled in is not an input
            return 1;
        } else return 0;
    };
    var start_validation = 0;
    //Filling in edit details inputs (after successful callback)
    var FillInPersonalDetailsInEditDetailsSuccess = function (data, status) {

        if (data.GetPersonalDetailsResult == false) {
            //Error - probably not logged in
            $(".edit_details_main").html("<strong>"+_("Error")+"</strong><br />" + data.errorMessage).show();
            return false;
        }
        $(".edit_details_main").show();

        //Filling in inputs
        var fill_in_array = new Array("StreetAddress",
        /*"PrimaryEmail",*/
        "HomePhone", "MobilePhone", "City", "CountyOrStateOrProvince", "PostCode");
        $(fill_in_array).each(function () {
            fill_in(this, data[this]);
        });
        fill_in("edit_details_FirstName", data.FirstName, 1);
        fill_in("edit_details_LastName", data.LastName, 1);
        fill_in("PrimaryEmail", data.PrimaryEmail, 1);
        //Selecting option which should be selected
        $("#choose_country [value=" + data.IDMMCountry + "]").attr("selected", "selected");
        //Binding action to choose_country select
        $("#choose_country").change(function () {
            changeCountry();
        });


        var nameEQ = "lang=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) {
                var lang_act = c.substring("lang=".length, c.length);
                break;
            }
        }

        $("#change_language [value=" + lang_act + "]").attr("selected", "selected");
        $("#change_language").change(function () {

            var date = new Date();
            date.setTime(date.getTime() + (days_to_expire * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
            var params = {
                "key": "lang",
                "val": $(this).val()
            };
            makeCall("Content", "store", params, store_Success, store_Error);
            document.cookie = "lang=" + $(this).val() + expires + "; path=/";
            $(".lang_country_message").html("<p>"+_("Language has been updated")+"</p>");

        });
        //Going through all mandatory input, checking if they are ok and binding actions
        start_validation = 1;
        $("#edit-details input:not(.optional),#edit-details textarea").each(function () {
            uWinAccount.EditDetailsValidate.form($(this));
            //CheckDetails(this,0);
            /* not sure if it is neccessary	$(this).keyup(function(e){
						CheckDetails(this,e);
				}); */
        });
        start_validation = 0;

//mz
$("#password_edit_details").val("");
uWinAccount.EditDetailsValidate.form($("#password_edit_details"));

    };
    var store_Success = function (data, status) {
        //data;
    };
    var store_Error = function (request, status, error) {
        //"error";
    };
    //Callback error
    var FillInPersonalDetailsInEditDetailsError = function (request, status, error) {
        $("#edit-details").prepend("<span class='error'>"+_("Internal database error.")+"<br />"+_("Please try again later.")+"</span>");
    };
    var balance = null;
    //Filling in inputs of edit details (making a call)
    this.FillInPersonalDetailsInEditDetails = function () {
        var params = {};

        makeCall("Customer", "GetPersonalDetails", params, FillInPersonalDetailsInEditDetailsSuccess, FillInPersonalDetailsInEditDetailsError);
        //	uWinAccount.api.ReturnCurrentBalance(".balance span",_("%currency%"));
    };

//account landing
this.generateAccountLanding = function () {
    var params = {};
    makeCall("Account", "GetBalances", params, generateAccountLandingSuccess, generateAccountLandingError);
};

var generateAccountLandingSuccess = function (data, status) {
       //data;
	$("#history-results-table tr:eq(1) td:eq(1)").html("€ " +data.tradingBalance);//used to be data.main
	$("#history-results-table tr:eq(1) td:eq(2)").html("€ "+data.casino);
	$("#history-results-table tr:eq(1) td:eq(3)").html("€ "+data.poker);

	$("#history-results-table tr:eq(2) td:eq(1)").html("€ " +data.free);
	$("#history-results-table tr:eq(2) td:eq(2)").html("€ "+data.casinoBonus);
	$("#history-results-table tr:eq(2) td:eq(3)").html(_("n/a"));

   };

var generateAccountLandingError = function (request, status, error) {
//error   
};
//end accoung landing
    //Already In
    var balance_obj;
    var balance_html;
    var balance = null;
    var progress = 0;
    this.ReturnCurrentBalance = function (obj, html) {
        //"here2";

        if (balance == null && progress == 0) {
            progress = 1;

            balance_html = html;

            balance_obj = obj;
            var params = {};
            makeCall("Account", "GetPrimaryAccount", params, ReturnBalanceSuccess, ReturnBalanceFailure);
        } else if (balance == null && progress == 1) {
            setTimeout("uWinAccount.api.ReturnCurrentBalance(" + obj + "," + html + ")", 100)
        } else if (balance != null) {
            $(obj).html(html + balance);

        }
    }
    var ReturnBalanceSuccess = function (data, status) {
        progress = 0;
       // balance = data.CurrentBalance;//used to be data.TradingBalance
		balance = data.TradingBalance;
        $(balance_obj).html(balance_html + balance);
    }
    var ReturnBalanceFailure = function (request, status, error) {
        //"error";
    }
//new

this.UpdateBalanceOnTop = function () {
	var params={};
	
     makeCall("Account", "GetBalances", params, UpdateBalanceOnTopSuccess, UpdateBalanceOnTopFailure);
   }
   var UpdateBalanceOnTopSuccess = function (data, status) {

	if (typeof(data) == 'object') {
	   $('#total_balance').html(sprintf("%0.2f", parseFloat(data.tradingBalance)+parseFloat(data.poker)+parseFloat(data.casino)));
	   $('#total_balance_2').html(sprintf("%0.2f", parseFloat(data.tradingBalance)+parseFloat(data.poker)+parseFloat(data.casino)));
	   $('#bal_sport_1').html(sprintf("%0.2f", parseFloat(data.tradingBalance)));
	   $('#bal_sport_2').html(sprintf("%0.2f", parseFloat(data.free)));
	   $('#bal_casino_1').html(sprintf("%0.2f", parseFloat(data.casino)));
	   $('#bal_casino_2').html(sprintf("%0.2f", parseFloat(data.casinoBonus)));
	   $('#bal_poker_1').html(sprintf("%0.2f", parseFloat(data.poker)));
	   $('#bal_poker_2').html(sprintf("%0.2f", parseFloat(data.pokerVip)));
}
   }
   var UpdateBalanceOnTopFailure = function (request, status, error) {
       //"error";
   }

    //Already In end
    //Validation of EditDetails after pressing submit button
    this.EditDetails = function (form_id, messages_edit_details) {

        //validation suceeded
        var params = {};
        makeCall("Customer", "GetPersonalDetails", params, EditDetailsSucces_1, EditDetailsError);

    };

    //Successful Getting personal Details
    var EditDetailsSucces_1 = function (data, status) {
        //Going through all fields despite password
        $("#edit-details input:not(#password_edit_details,.submit-button),#edit-details textarea").each(function () {
            //Updating data object
            data[$(this).attr("id")] = $(this).val();
        });
        //Creating object which should be sent
        var ojb = {
            "personalDetails": data,
            "password": $("#password_edit_details").val()
        }
        //$("#password_edit_details").val();
        //Making a call
        makeCall("Customer", "UpdatePersonalDetailsExt", ojb, EditDetailsSuccess, EditDetailsError);
    };

    //function which attemps to change country (first get all details)
    var changeCountry = function () {
        /* im not sure if country should be changed everytime the select is changed, or only after pressing submit button, but... */
        var params = {};
        makeCall("Customer", "GetPersonalDetails", params, ChangeCountry_1, EditDetailsError);
    };

    //Details downloaded attempt to change country
    var ChangeCountry_1 = function (data, status) {
        //Updating country field in object
        data['IDMMCountry'] = $("#choose_country").val();
        //Creating new object
        var ojb = {
            "personalDetails": data
        }
        //Sending data
        makeCall("Customer", "UpdatePersonalDetails", ojb, changeCountrySuccess, EditDetailsError);
    };

    //Function which starts when changing country succeeded
    var changeCountrySuccess = function (data, status) {
        //Changing country success - is there anything to do ?
        $(".lang_country_message").html("<p>"+_("Country has been updated.")+"</p>");
		var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
		var lang = 'en';

		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf ("lang=");
			if (c_start!=-1) {
				c_start=c_start + 5;
				c_end=document.cookie.indexOf (";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				lang = unescape(document.cookie.substring(c_start,c_end));
		    }
		}
		lang = lang.toLowerCase();
		var redeye = 'https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl='+url+'change-confirm&language='+lang+'&change_confirm=confirm&change_country='+$("#choose_country").val();
		$(".lang_country_message").append('<img src="'+redeye+'"/>');
    };

    /*
		//Functon to validate email address
		var isValidEmailAddress = function(emailAddress) {
			var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
			return pattern.test(emailAddress);
		};
		*/
    //Displaying error
    var textError = function (obj, messages_edit_details) {
        if (messages_edit_details[$(obj).attr("id")]) return messages_edit_details[$(obj).attr("id")];
        else return "";
    };
















    //bet details
    var pageNumberBet;
    var ToDate;
    var FromDate;
    this.generateBetDetails = function () {
        var now_date = new Date();

        var to_month = now_date.getMonth() + 1;
        if (to_month < 10) to_month = "0" + to_month;
        var to_day = now_date.getDate();
        
		//to_day = to_day - 1; //finsoft return to_day + 1 so i make it to -1
        if (to_day < 10) to_day = "0" + to_day;

        FromDate = "2009" + "-" + "12" + "-" + "01" + "T" + "00" + ":" + "00" + ":" + "00";
        ToDate = now_date.getFullYear() + "-" + to_month + "-" + to_day + "T" + 23 + ":" + 59 + ":" + 59;

        pageNumberBet = 0;
        var ojb = {
            "from": FromDate,
            "to": ToDate,
            "pageNumber": pageNumberBet,
            "pageSize": betsPerRequest,
            "orderBy": 0,
            "orderDesc": 1
        }
        makeCall("Betting", "GetBetHistoryDetails", ojb, getNextBetDetails, ViewUserHistoryError);

    }

    var getNextBetDetails= function (data, status) {
        //used to be without Get and result
        if (data.GetBetHistoryDetailsResult != undefined) {

            var ReturnedbetsPerRequest = data.GetBetHistoryDetailsResult.BetHistoryDetails.length;

            $(data.GetBetHistoryDetailsResult.BetHistoryDetails).each(function () {
/*
console.log(this.IDFOBet);
console.log($("#bet_id").html());
console.log("-------");*/
                if (this.IDFOBet==($("#bet_id").html())) {
                    var betPrice = 0;
                    if (this.OwnPriceUp != 0) betPrice = ((Math.round(this.OwnPriceUp / this.OwnPriceDown * 100) / 100)+1).toFixed(2);
                    var betTotalReturn = this.TotalReturn;
                    if (betTotalReturn == null) betTotalReturn = 0;


                    if ($("#" + this.IDFOBet.replace(".", "")).html() == null) {
                        var string_to_display = '<li id=' + this.IDFOBet.replace(".", "") + '><a href="#"><span class="open-bets-title">' + parseDateTime(this.TSAttempted) + ' ' + this.BetTypeName + ' - ' + this.SelectionName + '</span>';
                        string_to_display = string_to_display + '<span class="expand">'+_("Expand")+'</span>';
                        string_to_display = string_to_display + '<span class="open-bets-details">';
                        string_to_display = string_to_display + '<span><b>'+_("Your selections")+':</b></span><ol>';


                        string_to_display = string_to_display + '<li><span>' + this.EventName + '</span>';
                        string_to_display = string_to_display + '<span>' + parseDateTime(this.TSEventTime) + '</span>';
                        string_to_display = string_to_display + '<span>' + this.MarketName + '</span>';
                        string_to_display = string_to_display + '<span><b>' + this.SelectionName + ' @ ' + betPrice + ' for ' + this.WUnitStake + '</b></span></li></ol>';



                        string_to_display = string_to_display + '<span class="your-bets"><b>'+_("Your Bets")+'</b></span>';
                        string_to_display = string_to_display + '<span>'+_("Bet ID")+': ' + this.IDFOBet + ' </span>';
                        string_to_display = string_to_display + '<span>'+_("Bet Type")+': ' + this.BetTypeName + ' </span>';
                        string_to_display = string_to_display + '<span class="selections">'+_("Selections")+': ' + this.SelectionName + ' </span>';
                        string_to_display = string_to_display + '<span>'+_("Unit Stake")+': '+this.WUnitStake+'</span>';
                        string_to_display = string_to_display + '<span class="open-bets-total first">'+_("Total stake")+': '+_("%currency%")+'<span>' + parseFloat(this.TotalStake).toFixed(2) + '</span></span>';
                        string_to_display = string_to_display + '<span class="open-bets-total">'+_("Potential returns")+': '+_("%currency%")+'<span>' + parseFloat(this.PotentialReturn).toFixed(2) + '</span></span>';


                        if (this.IsFree != "1") string_to_display = string_to_display + '<span class="open-bets-total second">'+_("Free bets voucher")+': '+_("%currency%")+'<span>0.00</span></span>';
                        else string_to_display = string_to_display + '<span class="open-bets-total second">'+_("Free bets voucher")+': '+_("%currency%")+'<span>' + parseFloat(this.TotalStake).toFixed(2) + '</span></span>';
                        string_to_display = string_to_display + '</span></a></li>';

                        $(".open-bets-list").append(string_to_display);
                    } else {
                        $("#" + this.IDFOBet.replace(".", "") + " .open-bets-title,#" + this.IDFOBet.replace(".", "") + " .selections").append(", " + this.SelectionName);
                        var string_to_display = "";

                        string_to_display = string_to_display + '<li><span class="anotherLeg">' + this.EventName + '</span>';
                        string_to_display = string_to_display + '<span>' + parseDateTime(this.TSEventTime) + '</span>';
                        string_to_display = string_to_display + '<span>' + this.MarketName + '</span>';
                        string_to_display = string_to_display + '<span><b>' + this.SelectionName + ' @ ' + betPrice + ' for ' + this.WUnitStake + '</b></span></li>';

                        $("#" + this.IDFOBet.replace(".", "") + " ol").append(string_to_display);


              /*        var add = parseFloat($("#" + this.IDFOBet.replace(".", "") + " .first span").html()) + parseFloat(this.TotalStake);
                       $("#" + this.IDFOBet.replace(".", "") + " .first span").html(add.toFixed(2));

                        if (this.IsFree == "1") {
                            var add2 = parseFloat($("#" + this.IDFOBet.replace(".", "") + " .second span").html()) + parseFloat(this.TotalStake);
                            $("#" + this.IDFOBet.replace(".", "") + " .second span").html(add2);

                        } else {
                            var add2 = parseFloat($("#" + this.IDFOBet.replace(".", "") + " .second span").html());

                        }*/
                    }
                }
            });
        }
        pageNumberBet++;

        var ojb = {
            "from": FromDate,
            "to": ToDate,
            "pageNumber": pageNumberBet,
            "pageSize": betsPerRequest,
            "orderBy": 0,
            "orderDesc": 1
        }
        if (betsPerRequest == ReturnedbetsPerRequest) makeCall("Betting", "GetBetHistoryDetails", ojb, getNextBetDetails, ViewUserHistoryError);
        else {
            $(".open-bets-list").show();
            $(".please_wait").remove();
			$(".open-bets-details").slideDown();
            $('.content-tab').after('<span class="expand-all">'+_("Expand All")+'</span>');
            $(".open-bets-list li span.open-bets-title").click(function (e) {
	e.preventDefault();
                if ($(this).next("span.expand").next(".open-bets-details").css("display") == "none") {
                    $(this).next("span.expand").next(".open-bets-details").slideDown();
                    $(this).next("span.expand").addClass('collapse').text('Collapse');
                } else {
                    $(this).next("span.expand").next(".open-bets-details").slideUp();
                    $(this).next("span.expand").removeClass('collapse').text('Expand');
                }

            });
            $(".open-bets-list li span.expand").click(function () {
                if ($(this).next(".open-bets-details").css("display") == "none") {
                    $(this).next(".open-bets-details").slideDown();
                    $(this).addClass('collapse').text('Collapse');
                } else {
                    $(this).next(".open-bets-details").slideUp();
                    $(this).removeClass('collapse').text('Expand');
                }

            });

            $('.expand-all').click(function () {
                if ($(this).is('.collapse-all')) {
                    // hide all
                    $(this).removeClass('collapse-all');
                    $('.open-bets-list a span.expand').each(function () {
                        $(this).removeClass('collapse').text('Expand');
                    });
                    $('.open-bets-list a .open-bets-details').each(function () {
                        $(this).slideUp();
                    });
                }

                else {
                    // show all
                    $(this).addClass('collapse-all');
                    $('.open-bets-list a span.expand').each(function () {
                        $(this).addClass('collapse').text('Collapse');
                    });
                    $('.open-bets-list a .open-bets-details').each(function () {
                        $(this).slideDown();
                    });
                }

            });












            //done
        }
    }


    //end bet details




    //open bets
    var pageNumberOpen;
    var ToDate;
    var FromDate;
    this.generateOpenBets = function () {
        var now_date = new Date();

        var to_month = now_date.getMonth() + 1;
        if (to_month < 10) to_month = "0" + to_month;
        var to_day = now_date.getDate();
        //to_day = to_day - 1; //finsoft return to_day + 1 so i make it to -1
        if (to_day < 10) to_day = "0" + to_day;

        FromDate = "2009" + "-" + "12" + "-" + "01" + "T" + "00" + ":" + "00" + ":" + "00";
        ToDate = now_date.getFullYear() + "-" + to_month + "-" + to_day + "T" + 23 + ":" + 59 + ":" + 59;

        pageNumberOpen = 0;
        var ojb = {
            "from": FromDate,
            "to": ToDate,
            "pageNumber": pageNumberOpen,
            "pageSize": betsPerRequest,
            "orderBy": 0,
            "orderDesc": 1
        }
        makeCall("Betting", "GetBetHistoryDetails", ojb, getNextOpenBets, ViewUserHistoryError);

    }

    var getNextOpenBets = function (data, status) {
        //used to be without Get and result
        if (data.GetBetHistoryDetailsResult != undefined && data.GetBetHistoryDetailsResult.BetHistoryDetails!=undefined) {
            var ReturnedbetsPerRequest = data.GetBetHistoryDetailsResult.BetHistoryDetails.length;

            $(data.GetBetHistoryDetailsResult.BetHistoryDetails).each(function () {


                if (this.BetStateName == "Open"
                /*&& this.BetStateName!="Attempted"*/
                ) {

                    var betPrice = 0;
                    if (this.OwnPriceUp != 0) betPrice = ((Math.round(this.OwnPriceUp / this.OwnPriceDown * 100) / 100)+1).toFixed(2);

                    var betTotalReturn = this.TotalReturn;
                    if (betTotalReturn == null) betTotalReturn = 0;


                    if ($("#" + this.IDFOBet.replace(".", "")).html() == null) {
                        var string_to_display = '<li id=' + this.IDFOBet.replace(".", "") + '><a href="#"><span class="open-bets-title">' + parseDateTime(this.TSAttempted) + ' ' + this.BetTypeName + ' - ' + this.SelectionName + '</span>';
                        string_to_display = string_to_display + '<span class="expand">'+_("Expand")+'</span>';
                        string_to_display = string_to_display + '<span class="open-bets-details">';
                        string_to_display = string_to_display + '<span><b>'+_("Your selections")+':</b></span><ol>';


                        string_to_display = string_to_display + '<li><span>' + this.EventName + '</span>';
                        string_to_display = string_to_display + '<span>' + parseDateTime(this.TSEventTime) + '</span>';
                        string_to_display = string_to_display + '<span>' + this.MarketName + '</span>';
                        string_to_display = string_to_display + '<span><b>' + this.SelectionName + ' @ ' + betPrice + ' for ' + this.WUnitStake + '</b></span></li></ol>';



                        string_to_display = string_to_display + '<span class="your-bets"><b>'+_("Your Bets")+'</b></span>';
                        string_to_display = string_to_display + '<span>'+_("Bet ID")+': ' + this.IDFOBet + ' </span>';
                        string_to_display = string_to_display + '<span>'+_("Bet Type")+': ' + this.BetTypeName + ' </span>';
                        string_to_display = string_to_display + '<span class="selections">'+_("Selections")+': ' + this.SelectionName + ' </span>';
                        string_to_display = string_to_display + '<span>'+_("Unit Stake")+': '+this.WUnitStake+'</span>';
                        string_to_display = string_to_display + '<span class="open-bets-total first">'+_("Total stake")+': '+_("%currency%")+'<span>' + parseFloat(this.TotalStake).toFixed(2) + '</span></span>';
                        string_to_display = string_to_display + '<span class="open-bets-total">'+_("Potential returns")+': '+_("%currency%")+'<span>' + parseFloat(this.PotentialReturn).toFixed(2) + '</span></span>';


                        if (this.IsFree != "1") string_to_display = string_to_display + '<span class="open-bets-total second">'+_("Free bets voucher")+': '+_("%currency%")+'<span>0.00</span></span>';
                        else string_to_display = string_to_display + '<span class="open-bets-total second">'+_("Free bets voucher")+': '+_("%currency%")+'<span>' + parseFloat(this.TotalStake).toFixed(2) + '</span></span>';
                        string_to_display = string_to_display + '</span></a></li>';

                        $(".open-bets-list").append(string_to_display);
                    } else {
                        $("#" + this.IDFOBet.replace(".", "") + " .open-bets-title,#" + this.IDFOBet.replace(".", "") + " .selections").append(", " + this.SelectionName);
                        var string_to_display = "";

                        string_to_display = string_to_display + '<li><span class="anotherLeg">' + this.EventName + '</span>';
                        string_to_display = string_to_display + '<span>' + parseDateTime(this.TSEventTime) + '</span>';
                        string_to_display = string_to_display + '<span>' + this.MarketName + '</span>';
                        string_to_display = string_to_display + '<span><b>' + this.SelectionName + ' @ ' + betPrice + ' for ' + this.WUnitStake + '</b></span></li>';

                        $("#" + this.IDFOBet.replace(".", "") + " ol").append(string_to_display);


                      /*  var add = parseFloat($("#" + this.IDFOBet.replace(".", "") + " .first span").html()) + parseFloat(this.TotalStake);
                        $("#" + this.IDFOBet.replace(".", "") + " .first span").html(add.toFixed(2));

                        if (this.IsFree == "1") {
                            var add2 = parseFloat($("#" + this.IDFOBet.replace(".", "") + " .second span").html()) + parseFloat(this.TotalStake);
                            $("#" + this.IDFOBet.replace(".", "") + " .second span").html(add2);

                        } else {
                            var add2 = parseFloat($("#" + this.IDFOBet.replace(".", "") + " .second span").html());

                        }*/
                    }
                }
            });
        }
else{
	$(".please_wait").html(_("There are no current bets available"));
	return true;
}
        pageNumberOpen++;

        var ojb = {
            "from": FromDate,
            "to": ToDate,
            "pageNumber": pageNumberOpen,
            "pageSize": betsPerRequest,
            "orderBy": 0,
            "orderDesc": 1
        }
        if (betsPerRequest == ReturnedbetsPerRequest) makeCall("Betting", "GetBetHistoryDetails", ojb, getNextOpenBets, ViewUserHistoryError);
        else {
            $(".open-bets-list").show();
            $(".please_wait").remove();
            $('.content-tab').after('<span class="expand-all">'+_("Expand All")+'</span>');
            $(".open-bets-list li span.open-bets-title").click(function (e) {
	e.preventDefault();
                if ($(this).next("span.expand").next(".open-bets-details").css("display") == "none") {
                    $(this).next("span.expand").next(".open-bets-details").slideDown();
                    $(this).next("span.expand").addClass('collapse').text('Collapse');
                } else {
                    $(this).next("span.expand").next(".open-bets-details").slideUp();
                    $(this).next("span.expand").removeClass('collapse').text('Expand');
                }

            });
            $(".open-bets-list li span.expand").click(function () {
                if ($(this).next(".open-bets-details").css("display") == "none") {
                    $(this).next(".open-bets-details").slideDown();
                    $(this).addClass('collapse').text('Collapse');
                } else {
                    $(this).next(".open-bets-details").slideUp();
                    $(this).removeClass('collapse').text('Expand');
                }

            });

            $('.expand-all').click(function () {
                if ($(this).is('.collapse-all')) {
                    // hide all
                    $(this).removeClass('collapse-all');
                    $('.open-bets-list a span.expand').each(function () {
                        $(this).removeClass('collapse').text('Expand');
                    });
                    $('.open-bets-list a .open-bets-details').each(function () {
                        $(this).slideUp();
                    });
                }

                else {
                    // show all
                    $(this).addClass('collapse-all');
                    $('.open-bets-list a span.expand').each(function () {
                        $(this).addClass('collapse').text('Collapse');
                    });
                    $('.open-bets-list a .open-bets-details').each(function () {
                        $(this).slideDown();
                    });
                }

            });












            //done
        }
    }


    //end open bets
    var pageNumber;
    var pageNumberAccount;
    var betsPerRequest = 100;
    var balancePerRequest = 100;//used to be 100 but there were problems!
    var AccountId = 0;
    var ToDate;
    var FromDate;
    var progress = 0;
    this.ViewUserHistoryGenerate = function (from, to, type) {

        FromDate = from;
        ToDate = to;
        $(".betting_history_container").hide();
        $(".betting_history tr:gt(0)").remove();
        $(".balance_history_container").hide();
        $(".balance_history tr:gt(0)").remove();
        $(".please_wait").show();
        if (progress == 0) if (type == "bet") {
            pageNumber = 0;
            //var ojb = {
            //    "from": FromDate,
            //    "to": ToDate,
            //    "pageNumber": pageNumber,
            //    "pageSize": betsPerRequest,
            //    "orderBy": 0,
            //    "orderDesc": 1
            //}

            var ojb = [
                FromDate,
                ToDate,
                pageNumber,
                betsPerRequest,
                0,
				1
            ];

            makeCall("Betting", "GetBetHistoryDetails", ojb, getNextBettingHistory, ViewUserHistoryError);
        } else {
            pageNumberAccount = 0;
            ojb = {};
            makeCall("Account", "GetPrimaryAccount", ojb, ViewUserHistoryStartGenerating, ViewUserHistoryError);
        }
        progress = 1;
    }
    var ViewUserHistoryError = function (request, status, error) {

        //"error";
    }
    var ViewUserHistoryStartGenerating = function (data, status) {

        AccountId = data.IDMMAccount;
        //var ojb = {
        //    "IDMMAccount": AccountId,
        //    "from": FromDate,
        //    "to": ToDate,
        //    "pageNumber": pageNumberAccount,
        //    "pageSize": balancePerRequest,
        //    "orderBy": 0,
        //    "orderDesc": 1
        //};

        var ojb = [
            AccountId,
            FromDate,
            ToDate,
            pageNumberAccount,
            balancePerRequest,
            0,
            1
        ];

        makeCall("Account", "GetBalanceHistory", ojb, getNextBalanceHistory, ViewUserHistoryError);


    }
    var getNextBettingHistory = function (data, status) {
	if(window.location.host.match(/\.com/ig))
		var addr_bet="http://www.youwin.com/bet-details";
		else if(window.location.host.match(/\.tv/ig))
		var addr_bet="http://www.youwin.tv/bet-details";
		else
		var addr_bet=$(".bet_addr").html();

        if (data.GetBetHistoryDetailsResult != undefined && data.GetBetHistoryDetailsResult.BetHistoryDetails!=undefined) {
	
            var ReturnedbetsPerRequest = data.GetBetHistoryDetailsResult.BetHistoryDetails.length;
            $(data.GetBetHistoryDetailsResult.BetHistoryDetails).each(function () {

                //Date - Transaction name - Details - Amount - Balance
                //or
                //TSAttempted - EventName MakretName for SUniteStake @ OwnPriceUp/OwnPriceDown - BetState - amount - balance
                //var string_to_display = "<tr><td>"+this.TSAttempted+"</td><td>"+this.WUnitStake+"</td><td>"+this.MarketName +"- "+ this.BetTypeName+"</td><td>?</td><td>"+this.TotalStake/this.WUnitStake+"</td><td>"+this.EventName+"</td><td>"+betPrice+"</td><td>"+this.BetState+"</td><td>"+betTotalReturn+"</td><td>"+(this.TotalReturn-this.TotalStake).toFixed(2)+"</td></tr>";//+" "+this.+" "+this.+" "+this.;
                //	if(this.BetStateName!="Open" && this.BetStateName!="Attempted") {
                var betPrice = 0;
                if (this.OwnPriceUp != 0) betPrice = ((Math.round(this.OwnPriceUp / this.OwnPriceDown * 100) / 100)+1).toFixed(2);
                var betTotalReturn = this.TotalReturn;
                if (betTotalReturn == null) betTotalReturn = 0;
                //Shall THE BALANCE be 0 if BETSTATUS is open ?
                var string_to_display = "<tr><td>" + /*this.IDFOBet*/this.FullExternalReference + "</td><td>" + parseDateTime(this.TSAttempted) + "</td><td><a href='#' onclick=\"window.open('"+addr_bet+"?bet_id=" + this.IDFOBet + "','newWindow','width=568,scrollbars=1,height=500');\">" + this.EventName + " " + this.MarketName + " for " + this.WUnitStake + " @ " + betPrice + "</a></td><td>" ;
if(this.BetStateName=="Closed"){
if(this.WinWLDOutcome=="W") string_to_display = string_to_display+_("Won");
else if(this.WinWLDOutcome=="D") string_to_display = string_to_display+_("Draw");
else string_to_display = string_to_display+_("Lost");
}
else
string_to_display = string_to_display+this.BetStateName;

//string_to_display = string_to_display+ "</td><td>" + /*this.TotalStake / this.WUnitStake */this.BetTypeName + "</td><td>" + (this.TotalReturn - this.TotalStake).toFixed(2) + "</td></tr>";

string_to_display = string_to_display+ "</td><td>" + /*this.TotalStake / this.WUnitStake */this.BetTypeName + "</td><td>" + ((this.TotalReturn==null) ? parseInt(this.TotalReturn - this.TotalStake).toFixed(2):parseInt(this.TotalReturn).toFixed(2)) + "</td></tr>";
                $(".betting_history").append(string_to_display);
                //	}
            });
        }
        pageNumber++;
        //ToDate;
        //var ojb = {
        //    "from": FromDate,
        //    "to": ToDate,
        //    "pageNumber": pageNumber,
        //    "pageSize": betsPerRequest,
        //    "orderBy": 0,
        //    "orderDesc": 1
        //}
        var ojb = [
            FromDate,
            ToDate,
            pageNumber,
            betsPerRequest,
            0,
            1
        ];

        if (betsPerRequest == ReturnedbetsPerRequest) makeCall("Betting", "GetBetHistoryDetails", ojb, getNextBettingHistory, ViewUserHistoryError);
        else {
            //done so!
            $(".betting_history_container").show();
            progress = 0;
            $(".please_wait").hide();

        }
    }

    var getNextBalanceHistory = function (data, status) {
	if(window.location.host.match(/\.com/ig))
		var addr_bet="http://www.youwin.com/bet-details";
		else if(window.location.host.match(/\.tv/ig))
		var addr_bet="http://www.youwin.tv/bet-details";
		else
		var addr_bet=$(".bet_addr").html();
		
        //BALANCE
        if (data.BalanceHistoryDetails != undefined) {
            var ReturnedBalancePerRequest = data.BalanceHistoryDetails.length;
            if (ReturnedBalancePerRequest == undefined) ReturnedBalancePerRequest = 1;
            $(data.BalanceHistoryDetails).each(function () {
                var text = this.Hint; // to
                if (text != null) {
                    var tmp_split = text.split("#");
                    var info;

                    if (tmp_split.indexOf(':') != -1) {
                        info = tmp_split[2].split(":")[1] + ' : ' + tmp_split[2].split(":")[0];
                    } else {
                        info = tmp_split;
                    }

                    text = "<td>" + tmp_split[1] + "</td><td><a href='#' onclick=\"window.open('"+addr_bet+"?bet_id=" + tmp_split[0] + "0','newWindow','width=568,scrollbars=1,height=500');\">" + info + "</a></td>";
                    if (tmp_split[1] == undefined) text = "<td colspan='2'>" + this.Hint + "</td>"; //or this.Description
                } else text = "<td colspan='2'>" + this.Description + "</td>";
                //	var showValue = this.AmountCredit;
                //	if(showValue==0) 
                //	showValue = "-"+this.AmountDebit;
                //	else 
                //	showValue = "+"+showValue;
                /*
					<td>%date%</td><td>%type%</td><td><a href="restcallforReceipt?ID=%BidID%">%type% : %name%</a></td><td>%deposit%</td><td>%withdraw%</td><td>%currentbalance%</td>
					*/
                AmountCreditD = this.AmountCredit;
                if (this.AmountCredit != 0) AmountCreditD = AmountCreditD;
                AmountDebitD = this.AmountDebit;
                if (this.AmountDebit != 0) AmountDebitD = "-" + AmountDebitD;
                var string_to_display = "<tr><td>" + parseDateTime(this.ValueDate, 1) + "</td>" + text + "<td>" + AmountDebitD + "</td><td>" + AmountCreditD + "</td><td>" + this.CurrentBalance + "</td></tr>";
                $(".balance_history").append(string_to_display);

            });
        }
        pageNumberAccount++;
        //var ojb = {
        //    "IDMMAccount": AccountId,
        //    "from": FromDate,
        //    "to": ToDate,
        //    "pageNumber": pageNumberAccount,
        //    "pageSize": balancePerRequest,
        //    "orderBy": 0,
        //    "orderDesc": 1
        //};
        var ojb = [
            AccountId,
            FromDate,
            ToDate,
            pageNumberAccount,
            balancePerRequest,
            0,
            1
        ];
        if (balancePerRequest == ReturnedBalancePerRequest) makeCall("Account", "GetBalanceHistory", ojb, getNextBalanceHistory, ViewUserHistoryError);
        else {
            $(".balance_history_container").show();
            progress = 0;
            $(".please_wait").hide();
        }

    }

    this.user_login = function () {
        var password = $(".password_in").val();
        var username = $(".username_in").val();
        uWinAccount.api.login(username, password);

    }



    /*	this.check_logging=function(){
					var params={};
					makeCall("Customer", "isLoggedIn", params, check_logging_s2, check_logging_e);

			}
			*/
    var check_logging_s2 = function (data, status) {

    }

    var parseDateTime = function (arg, is_date) {
        var str1 = arg.split("T");
        var str2 = str1[0].split("-");
        var str3 = str1[1].split(":");
        var to_return = str2[2] + "/" + str2[1] + "/" + str2[0];
        if (is_date != 1) to_return = to_return + " " + str3[0] + ":" + str3[1];
        return to_return;
    }
    this.checkLoggedIn = function (sel) {

        if (logged_in == 2) {
            setTimeout("uWinAccount.api.checkLoggedIn('" + sel + "')", 100);
            return false;
        }
        if (logged_in == 0) {
            $(sel).html(_("You are not logged in, please login or")+" <a href=\""+register_link+"\">"+_("register")+"</a>");
        }
    }
    //
    var checkPasswordGSuccess = function (data, status) {
        if (data == true) {
            uWinAccount.EditDetailsValidate.passwordCheck = 2;
            uWinAccount.EditDetailsValidate.errorCount += 0;
            uWinAccount.EditDetailsValidate.fieldOk();
        } else {
            uWinAccount.EditDetailsValidate.passwordCheck = 3;
            uWinAccount.EditDetailsValidate.errorCount += 1;
            uWinAccount.EditDetailsValidate.fieldFail("", uWinAccount.EditDetailsValidate.currentMsg);
        }
        uWinAccount.EditDetailsValidate.ajaxRun = false;
        uWinAccount.EditDetailsValidate.handleSubmitButton();
    };
    var checkPasswordGError = function (request, status, error) {
        uWinAccount.debug("Failed to check login availability", request, status, error);
        uWinAccount.EditDetailsValidate.ajaxRun = false;
    };

    this.checkPasswordG = function (password) {
        var params = [
        password];
        makeCall("Customer", "CheckPassword", params, checkPasswordGSuccess, checkPasswordGError);
        return true;
    };
    var checkPasswordESuccess = function (data, status) {
        if (data == true) {
            uWinAccount.ChangePasswordValidate.passwordCheck = 2;
            uWinAccount.ChangePasswordValidate.errorCount += 0;
            uWinAccount.ChangePasswordValidate.fieldOk();
        } else {
            uWinAccount.ChangePasswordValidate.passwordCheck = 3;
            uWinAccount.ChangePasswordValidate.errorCount += 1;
            uWinAccount.ChangePasswordValidate.fieldFail("", uWinAccount.ChangePasswordValidate.currentMsg);
        }
        uWinAccount.ChangePasswordValidate.ajaxRun = false;
        uWinAccount.ChangePasswordValidate.handleSubmitButton();
    };
    var checkPasswordEError = function (request, status, error) {
        uWinAccount.debug("Failed to check login availability", request, status, error);
        uWinAccount.ChangePasswordValidate.ajaxRun = false;
    };

    this.checkPasswordE = function (password) {
        var params = [
        password];
        makeCall("Customer", "CheckPassword", params, checkPasswordESuccess, checkPasswordEError);
        return true;
    };
    var checkPasswordSSuccess = function (data, status) {
        if (data == true) {
            uWinAccount.SetDepositLimitValidate.passwordCheck = 2;
            uWinAccount.SetDepositLimitValidate.errorCount += 0;
            uWinAccount.SetDepositLimitValidate.fieldOk();
        } else {
            uWinAccount.SetDepositLimitValidate.passwordCheck = 3;
            uWinAccount.SetDepositLimitValidate.errorCount += 1;
            uWinAccount.SetDepositLimitValidate.fieldFail("", uWinAccount.SetDepositLimitValidate.currentMsg);
        }
        uWinAccount.SetDepositLimitValidate.ajaxRun = false;
        uWinAccount.SetDepositLimitValidate.handleSubmitButton();
    };
    var checkPasswordSError = function (request, status, error) {
        uWinAccount.debug("Failed to check login availability", request, status, error);
        uWinAccount.SetDepositLimitValidate.ajaxRun = false;
    };

    this.checkPasswordS = function (password) {
        var params = [
        password];
        makeCall("Customer", "CheckPassword", params, checkPasswordSSuccess, checkPasswordSError);
        return true;
    };
    /* End Functions by Jaroslaw Salwa */




    //JS START
    //var logged_in=2;
    this.user_login = function () {
        var password = $(".password_in").val();
        var username = $(".username_in").val();
        uWinAccount.api.login(username, password);

    }



    this.check_logging = function () {
        var params = {};
        makeCall("Customer", "isLoggedIn", params, check_logging_s, check_logging_e);

    }
    /*	this.checkLoggedIn = function(sel){
			
			if(logged_in==2) {setTimeout("uWinAccount.api.checkLoggedIn('"+sel+"')",100); return false;}
			if(logged_in==0){
				$(sel).html("You are not logged in, please login or  <a href=\""+register_link+"\">"+_("register")+"</a>");
			}
		}*/
    var check_logging_s = function (data, status) {
        if (data != false) {
            logged_in = 1;
            //$("#login-box").html("Hello "+data+"! <a href='#' class='logout'>Logout</a><img class='flag' src='./?a=224'/>");
            //$("#login-box").html('<img class="flag" src="mysource_files/en-flag.jpg"/><input type="submit" class="logout-button" value=""/><p id="deposit-link"><span>Deposit</span></p><p id="account-link"><span>My Account</span></p><p class="show-balance"><span class="left">â‚¬25.00</span><span class="right">Hide</span></p>');
            //$("#login-box").html('<img class="flag" src="mysource_files/en-flag.jpg"/><input type="submit" class="logout-button" value=""/><p id="deposit-link"><a href="./?a=4017"><span>Deposit</span></a></p><p id="account-link"><a href="./?a=3729"><span>My Account</span></a></p><p class="show-balance"><span class="left">â‚¬25.00</span><span class="right">Hide</span></p>');

            uWinAccount.api.ReturnCurrentBalance($(".hide_b .left, .balance span"), _("%currency%"));//, #history-details .balance
            $(".show_b").click(function (e) {
                e.preventDefault();
               	    $(".show_b").hide();
	 $(".hide_b").show();
            });
			$(".hide_b .right a").click(function (e) {
                e.preventDefault();
                $(".hide_b").hide();
 $(".show_b").show();
            });
            $(".not_logged_in_top").remove();
            $(".logged_in_top").show();

if ($('#Loged_in_transfer').length) {
	$('#casino_transfer_balance').css('display','block');
	$('#casino-info div.transfer').css('display','block');
}

            $(".logout-button").click(function () {
                var params = {};
                makeCall("Customer", "Logout", params, logout_s, logout_e);
            });
        } else {
            logged_in = 0;
            //$(".logged_in_top").remove();
$(".logged_in_top").hide();
            $(".not_logged_in_top").show();
        }
    }
    var check_logging_e = function (request, status, error) {
        //"error!"
    }
    var logout_e = function (request, status, error) {
        //"error!"
    }
    var logout_s = function (data, status) {
        //"done";
        window.location.reload();
    }
    //already in
    var balance_obj;
    var balance_html="â‚¬";
    var balance = null;
    var progress = 0;
    this.ReturnCurrentBalance = function (obj, html) {
	//stopped using html and instead downloading CurrencyNotation
        if (html != null) balance_html = html;
        if (obj != null) balance_obj = obj;
        if (balance == null && progress == 0) {
            progress = 1;

            var params = {};
            makeCall("Account", "GetBalances", params, ReturnBalanceSuccess, ReturnBalanceFailure);
        } else if (balance == null && progress == 1) {
            setTimeout("uWinAccount.api.ReturnCurrentBalance(null,null)", 100)
        } else if (balance != null) {
            balance_obj.html(balance_html + balance);

        }
    }
    var ReturnBalanceSuccess = function (data, status) {
        progress = 0;
        if (typeof(data) == 'object') {
		    if (window.location.host.match(/poker/g)) {
				balance = parseFloat(data.poker);
			} else if (window.location.host.match(/casino/g)) {
		    	balance = parseFloat(data.casino);
				if ($("#casino-info").length > 0) {
					$("#casino-info ul li:eq(0) h3").text("Balances");
					$("#casino-info ul li:eq(1)").html('Casino Balance <span class="numbers">'+_('%currency%')+' '+data.casino+'</span>');
					$("#casino-info ul li:eq(2)").html('Casino Bonus <span class="numbers">'+_('%currency%')+' '+data.casinoBonus+'</span>');
				}
			} else {
        		balance = parseFloat(data.tradingBalance)+parseFloat(data.poker)+parseFloat(data.casino);
			}
balance=balance.toFixed(2);
//balance_html=data.CurrencyNotation;
        	balance_obj.html(balance_html + balance);
        }
    }
    var ReturnBalanceFailure = function (request, status, error) {
        //"error"
    }
    //Already in end
    //JS STOP
    /**
     *	Login
     *	Los a user into finsoft's system
     */
	var loginUserName;
	var loginShowModal = function(comm,header,additional){
	if($(".black_overlay").html()==null)
	$("body").prepend("<div class='black_overlay'></div>");
		$("body").prepend("<div class=\"black_overlay_2\"><div class=\"login_message_error\"><span>"+header+"</span><p>"+comm+"</p><div class='imgloader'></div></div></div>");
		if(additional==1) $(".imgloader").append("<img src='./?a=5372' />");
		if($(".black_overlay_2").length>1)
		$(".black_overlay_2:last").remove();
		$(".login_message_error").bind("click",function(e){
			e.preventDefault();
			$(".black_overlay").remove();
			$(".black_overlay_2").remove();
		});
		var yScroll;
		if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		} else if (document.body) { // all other Explorers
		yScroll = document.body.scrollTop;
		}
		if($("#container #footer").height()==null)
		$(".black_overlay").css("height", parseInt($("#header").height())+parseInt($("#container").height())+parseInt($("#footer").height()));
		else
		$(".black_overlay").css("height", parseInt($("#header").height())+parseInt($("#container").height()));
		$(".login_message_error").css("margin-top",(Math.ceil($(window).height()/2)+yScroll)-60);
	}
    var loginSuccess = function (data, status) {
		if(data.WCFApplicationException!=null){
			//console.log(data.WCFApplicationException.Message); 
			//some exception
			loginShowModal(_(data.WCFApplicationException.Message),_("Error"));
		}
		else{
			//ok
			uWinAccount.debug(data);
			if (data.LoginResult) { 
				var lang = 'en';

				if (document.cookie.length>0) {
					c_start=document.cookie.indexOf ("lang=");
					if (c_start!=-1) {
						c_start=c_start + 5;
						c_end=document.cookie.indexOf (";",c_start);
						if (c_end==-1) c_end=document.cookie.length;
						lang = unescape(document.cookie.substring(c_start,c_end));
				    }
				}
				lang = lang.toLowerCase();

				if (data.PokerRedir) {
					var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
					var redeye = 'https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl='+url+'logon-confirm&language='+lang+'&logon_confirm=confirm&username='+loginUserName;
					loginShowModal (_("Successfully logged in. Please wait.")+'<img src="'+redeye+'"/>', _("Logged in")); 

					var msg = _("It seems that you don't have a Poker account set up already. Press OK to create a poker account, or press Cancel to continue."); 
					if (confirm(msg)) {
						window.location='https://myaccount.youwin.com/'+lang+'/poker/poker-nickname';
					} else {
						window.location.reload();
					}
						
				} else {
					var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
					var redeye = 'https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl='+url+'logon-confirm&language='+lang+'&logon_confirm=confirm&username='+loginUserName;
					loginShowModal (_("Successfully logged in. Please wait.")+'<img src="'+redeye+'"/>', _("Logged in")); 
					window.setTimeout(function () {window.location.reload();}, 1000);
				}	
		        uWinAccount.debug("API login success", data); 
			}
		}
    };
    var loginError = function (request, status, error) {
        //uWinAccount.ui.error( _("Login Failed"));
		//console.log("test");
		loginShowModal( _("Login failed. Server is not working"), _("Error"));
        uWinAccount.debug("Login API failed", request, status, error);
    };

    this.login = function (username, password) {
		//starting loging
        loginUserName = username;
		var params = [
        username, password];
        loginShowModal(_("Please wait..."), _("Logging in"), 1);
        makeCall("Customer", "Login", params, loginSuccess, loginError);
    };

    this.login2 = function (username, password, successCallback) {
		var params = [
        username, password];
        makeCall("Customer", "NewLogin", params, successCallback);
    };

    this.getServerTime = function (successCallback) {
		var params = [];
        makeCall("Customer", "GetTime", params, successCallback);
    };

    this.logout2 = function (successCallback) {
		var params = [];
        makeCall("Customer", "Logout", params, successCallback);
    };

    var getAllowedBetTypesSuccess = function (data, status) {
        uWinAccount.debug("getAllowedBetTypesSuccess", data);
    };
    var getAllowedBetTypesError = function (request, status, error) {
        uWinAccount.debug("getAllowedBetTypesError", request, status, error);
    };
    this.getAllowedBetTypes = function (texasContext, bet) {
        var params = [
        texasContext, bet];
        makeCall("Betting", "GetAllowedBetTypes", params, getAllowedBetTypesSuccess, getAllowedBetTypesError);
    };



    // registerCustomer
    var registerCustomerSuccess = function (data, status) {
        /*if (data.WCFApplicationException) {
            uWinAccount.ui.error("Failed to register. " + data.WCFApplicationException.Message);
            //uWinAccount.debug("Failed to register. " + data.WCFApplicationException.Message, request, status, error);
        } else {
            //4017
            var params = [params_UserName, params_Password];
            makeSyncCall("Customer", "Login", params, registerLoginSuccess, registerLoginError);
			
			//$('form:first').submit();
            //uWinAccount.debug("Registration completed", data);
        }*/
		uWinAccount.debug("Registration completed", data);
    };
    var registerLoginSuccess = function () {
    }
    var registerLoginError = function () {
    }

    var registerCustomerError = function (request, status, error) {
        uWinAccount.ui.error(_("Failed to register"));
        uWinAccount.debug("Failed to register", request, status, error);
    };
    var params_Password = "";
    var params_UserName = "";

    this.registerCustomer = function (customer, nickname, language, btag) {


        var date = new Date();
        date.setTime(date.getTime() + (days_to_expire * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
        var params = {
            "key": "lang",
            "val": customer.IDDCLanguage.toLowerCase()
        };
        document.cookie = "lang=" + customer.IDDCLanguage.toLowerCase() + expires + "; path=/";
        makeSyncCall("Content", "store", params, store_Success, store_Error);


        obj = {
            "details": customer,
            "nickname": nickname,
            "language": language,
            "btag":	btag
        };

        params_Password = customer.Password;
        params_UserName = customer.UserName;
        //obj;

        return makeSyncCall("Customer", "RegisterFixedOddsCustomer", obj, registerCustomerSuccess, registerCustomerError);
        
    };

    // checkLoginAvailability
    var checkLoginAvailabilitySuccess = function (data, status) {
        if (data == true) {
            uWinAccount.registerValidate.loginCheck = 2;
            uWinAccount.registerValidate.errorCount += 0;
            uWinAccount.registerValidate.fieldOk();
        } else {
            uWinAccount.registerValidate.loginCheck = 3;
            uWinAccount.registerValidate.errorCount += 1;
            uWinAccount.registerValidate.fieldFail("", _("Login is already taken"));
            uWinAccount.api.suggestAvailableUsernames(uWinAccount.registerValidate.currentElement.val(), $("#q1786_q2").val(), $("#q1786_q3").val(), $("#q1786_q4").val());
        }
        uWinAccount.registerValidate.ajaxRun = false;
        uWinAccount.registerValidate.handleSubmitButton();
    };
    var checkLoginAvailabilityError = function (request, status, error) {
        uWinAccount.debug("Failed to check login availability", request, status, error);
        uWinAccount.registerValidate.ajaxRun = false;
    };

    this.checkLoginAvailability = function (login) {
        var params = [
        login];
        makeCall("Customer", "IsUsernameAvailable", params, checkLoginAvailabilitySuccess, checkLoginAvailabilityError);
        return true;
    };


    // checkLoginAvailability
    var checknicknameAvailabilitySuccess = function (data, status) {

        if (data == true) {
            uWinAccount.registerValidate.nicknameCheck = 2;
            uWinAccount.registerValidate.errorCount += 0;
            uWinAccount.registerValidate.fieldOk(uWinAccount.registerValidate.currentElement2);
        } else {
            uWinAccount.registerValidate.nicknameCheck = 3;
            uWinAccount.registerValidate.errorCount += 1;
            uWinAccount.registerValidate.fieldFail(uWinAccount.registerValidate.currentElement2, uWinAccount.registerValidate.currentMsg);
        }
        uWinAccount.registerValidate.ajaxRun = false;
        uWinAccount.registerValidate.handleSubmitButton();
    };

    var checknicknameAvailabilityError = function (request, status, error) {
        uWinAccount.debug("Failed to check login availability", request, status, error);
        uWinAccount.registerValidate.ajaxRun = false;
    };

    this.checknicknameAvailability = function (nickname) {
        var params = ["null", nickname];
        makeCall("Account", "PngValidateUser", params, checknicknameAvailabilitySuccess, checknicknameAvailabilityError);
        return true;
    };

    // suggestAvailableUsernames
    var suggestAvailableUsernamesSuccess = function (data, status) {
        //is that important?
        //	if (uWinAccount.registerValidate.currentMsg != '') {
        var names_numbers = new Array("one", "two", "three");

        if (uWinAccount.registerValidate.currentElement.parent().find(".suggested_usernames").html() == null) uWinAccount.registerValidate.currentElement.parent().find(".error-message").append('<div class="bg"><div class="list"><p>'+_("Username taken.")+'</p><p class="sec">'+_("Suggestions")+':</p><ul class="suggested_usernames"></ul></div></div><div class="bottom"></div>');
        else uWinAccount.registerValidate.currentElement.parent().find(".suggested_usernames li").remove();

        for (var i = 0; i < 3; i++) {

            uWinAccount.registerValidate.currentElement.parent().find(".suggested_usernames").append("<li id='" + names_numbers[i] + "'>" + data[i] + "</li>");
        }

        // }
    };
    var suggestAvailableUsernamesError = function (request, status, error) {
        uWinAccount.debug("Couldn't get available login names", request, status, error);
    };
    this.suggestAvailableUsernames = function (login, firstName, lastName, dateOfBirth) {
        var params = [
        login, firstName, lastName, dateOfBirth];
        //"making a call";
        return makeCall("Customer", "SuggestAvailableUsernames", params, suggestAvailableUsernamesSuccess, suggestAvailableUsernamesError);
    };

    this.setDepositLimitFillIn = function () {
        var params = {};
        makeCall("Account", "GetPrimaryAccount", params, setDepositLimitFillInSuccess, setDepositLimitFillInFailure);


    }
    var setDepositLimitFillInFailure = function (request, status, error) {
        //failure
    }
    var setDepositLimitFillInSuccess = function (data, status) {

        if (data) {
            if (data.DepositLimitInPeriod == null) $(".deposit_limit_all").hide();
            if (data.PendingDepositLimit == null) $(".pending_deposit_limit_all").hide();
            $(".deposit_limit_normal").html(data.DepositLimitInPeriod);
            $(".pending_deposit_limit_normal").html(data.PendingDepositLimit + data.CurrencyNotation);
            if (data.TSPendingLimitActivation != null) {
                var str1 = data.TSPendingLimitActivation.split("T");
                var str2 = str1[0].split("-");
                var str3 = str1[1].split(":");
                var to_return = str2[2] + "/" + str2[1] + "/" + str2[0];
                to_return = to_return + " " + str3[0] + ":" + str3[1];
                $(".pending_deposit_limit_time").html(to_return);
            }
            AccountId = data.IDMMAccount;
        }
    }
    this.setDepositLimit = function () {
        var params = [
        $("#password").val()];
        makeCall("Customer", "CheckPassword", params, setDepositLimitSuccess, setDepositLimitError);
    }
    var setDepositLimitError = function (request, status, error) {
        //failure
    }
    var setDepositLimitSuccess = function (data, status) {
        if (data) {
            params = {
                "IDMMAccount": AccountId,
                "IDMMPeriodUnit": $("#DepositPeriod").val(),
                "limit": $("#DepositLimit").val()
            };
            makeCall("Account", "SetDepositLimit", params, SetDepositLimitSuccess2, SetDepositLimitError2);

        } else {
            $(".set_deposit_limit").html("Error");
        }
    }
    var SetDepositLimitSuccess2 = function (data, status) {
        $(".set_deposit_limit").html("<p>"+_("Your Deposit limit is now set and waiting for activation.")+"</p>");
    }
    var SetDepositLimitError2 = function (request, status, error) {
        //failure
    }
	this.GetSecretQuestionTest=function(username,date){
		 var params = {"username":username,"date":date};
	        makeCall("Customer", "GetSecretQuestion", params, GetSecretQuestionTestSuccess, GetSecretQuestionError);
	}

	var GetSecretQuestionTestSuccess=function(data,status){
	if(data.SecretQuestion==null)
	{
		uWinAccount.api.SecretFail=0;
		$(".get_security_question_error").html(_("Incorrect data"));
	}
	else
	{
			uWinAccount.api.SecretFail=1;
		$("#form_email_5199_submit").trigger("click");
		
	}
	}
this.SecretFail=0;
	 
this.GetSecretQuestion=function(username,date){
	 var params = {"username":username,"date":date};
        makeCall("Customer", "GetSecretQuestion", params, GetSecretQuestionSuccess, GetSecretQuestionError);
}
var secretIDDC;
var GetSecretQuestionSuccess=function(data,status){


	$(".forgotten_question").html(_(data.SecretQuestion.Question));
	secretIDDC=data.SecretQuestion.IDDCSecretQuestion;
	$("#q5202_q6").val(secretIDDC);	

}

   var GetSecretQuestionError = function (request, status, error) {
       //failure
	$(".get_security_question_error").html("Error!");
   }
this.SetPasswordUsingSQuestion=function(username,answer,password,iddcq){
	var params = {"username":username,"IDCCQuestion":iddcq,"answer":answer,"password":password};
        makeCall("Customer", "SetPasswordUsingSecretAnswer", params, SetPasswordUsingSQuestionSuccess, SetPasswordUsingSQuestionError);
}
var SetPasswordUsingSQuestionSuccess=function(data,status){
	if(data==null){//ok
		$(".setpasswrduque").html(_("Password successfully changed."));
		}
		else{
		$(".setpasswrduque").html(_("Password was not changed")+" - "+ _(data.WCFApplicationException.Message));
		
	}
}
var SetPasswordUsingSQuestionError = function (request, status, error) {
    //failure
}
} (jQuery);



//setdepositlimit

uWinAccount.SetDepositLimitValidate = new

function ($) {
    var self = this;
    this.errorCount = 0;
    this.passwordCheck = 0;
    this.ajaxRun;
    this.currentElement;
    this.currentMsg;
    this.required;
    this.messages;
    this.inputs;
    this.checked_fields = Object();

    this.construct = function (required, messages, inputs) {
        this.required = required;
        this.messages = messages;
        this.inputs = inputs;
        this.inputs.each(function () {
            self.checked_fields[$(this).attr("id")] = 0;
        });
    };

    // function that validates on reg exp
    this.standard_field = function (element, expression, msg) {
        // first check if empty
        if (element.val() == "") {
            // this handles diffrent message for required fields
            if (this.required[element.attr("id")]) {

                // when msg not empty, it means we are on the current field || this.messages[element.attr("id")]!="" && start_validation==1, so need to display default as field is empty
                if (msg != "") msg = _("This field is required");

                this.fieldFail(element, msg);
                return 1;
            } else {
                this.fieldOk(element);
                return 0;
            }
        } else {
            // this checks regular expression
            if (element.val().match(expression)) {
                if (element.val().match(/^ +$/) && this.required[element.attr("id")]) {
                    this.fieldFail(element, msg);
                    return 1;
                } else {
                    this.fieldOk(element);
                    return 0;
                }
            } else {
                this.fieldFail(element, msg);
                return 1;
            }
        }
    };





    // handles display on correct field
    this.fieldOk = function (element) {
        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {
            element.parent().children("span.error-message").remove();
            //element.next("span").removeClass("fail");
            //element.next("span").addClass("accept");
        }
    };

    // handles display on wrong field	
    this.fieldFail = function (element, msg) {

        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {

            element.parent().children("span.error-message").remove();
        //    element.next("span").removeClass("accept");
       //     element.next("span").addClass("fail");
            if (msg == "") {
                element.parent().children("span.error-message").remove();
            } else {

                element.parent().append("<span class=\"error-message\">" + msg + "</span>");
            };
        }
    };


    // validates login field
    var previous_check;
    this.password_field = function (element, expression, length, current, msg) {
        this.currentElement = element;
        this.currentMsg = msg;
        if (element.val() == "") {
            if (msg != "") msg = _("This field is required");
            this.fieldFail(element, msg);
            return 1;
        } else {
            if (element.val().length < length) {
                this.fieldFail(element, _("Bad Password"));
                return 1;
            } else {
                // if current is not login field and was checked before (!=1), we will not run request
                if (current.attr("id") != element.attr("id") && this.passwordCheck > 0) {
                    // value 2 means previously field was validated as ok
                    if (this.passwordCheck == 2) {
                        this.fieldOk(element);
                        return 0;
                    }
                    // value 3 means previously field was validated as false
                    if (this.passwordCheck == 3) {
                        this.fieldFail(element, msg);
                        return 1;
                    }
                }
                this.ajaxRun = true;
                clearTimeout(previous_check);
                previous_check = setTimeout(" uWinAccount.api.checkPasswordS('" + element.val() + "')", 300);

                // always return 0 , additional check in makeCall
                return 0;
            }

        }
    };



    this.form = function (current) {
        this.errorCount = 0;
        this.ajaxRun = false;
        var mark_check = true;
        // goes through all inputs
        this.inputs.each(function () {
            // if current element, add error message to display, otherwise reset it to empty
            if ($(this).attr("id") == current.attr("id")) {
                msg = self.messages[current.attr("id")];
                self.checked_fields[$(this).attr("id")] = 1;
            } else {
                // if we didn't loop over current (mark_check is still true), than set array element to 1
                if (mark_check) {
                    self.checked_fields[$(this).attr("id")] = 1;
                };
                msg = "";
            };
            switch ($(this).attr("id")) {
            case "DepositLimit":
                self.errorCount += self.standard_field($(this), /^[0-9]+$/, msg, 1);
                break;

            case "password":
                self.errorCount += self.password_field($(this), /^[a-zA-Z0-9_.-ßäöüÄÖÜ&$*]+$/, 6, current, msg);
                break;
            default:
                break;
            };
            // if loop is on currently checked, than set mark_check to false
            if ($(this).attr("id") == current.attr("id")) {
                mark_check = false;
            };
        });
        this.handleSubmitButton();
    };

    this.handleSubmitButton = function () {
        if (!this.errorCount) {
            if (!this.ajaxRun) {
                document.getElementById("submit").disabled = false;
                $(".submit-button").addClass("green");
				$(".submit-button").attr("style","cursor:pointer;");
                $(".submit-button").parent('p').prev("div.arrow").addClass("arrow-green");
            }
        } else {

            document.getElementById("submit").disabled = true;
            $(".submit-button").removeClass("green");
			$(".submit-button").attr("style","");
            $(".submit-button").parent('p').prev("div.arrow").removeClass("arrow-green");
        }
    };

} (jQuery);



//change passwd
uWinAccount.ChangePasswordValidate = new

function ($) {
    var self = this;
    this.errorCount = 0;
    this.passwordCheck = 0;
    this.ajaxRun;
    this.currentElement;
    this.currentMsg;
    this.required;
    this.messages;
    this.inputs;
    this.checked_fields = Object();

    this.construct = function (required, messages, inputs) {
        this.required = required;
        this.messages = messages;
        this.inputs = inputs;
        this.inputs.each(function () {
            self.checked_fields[$(this).attr("id")] = 0;
        });
    };

    // function that validates on reg exp
    this.standard_field = function (element, expression, msg) {
        // first check if empty
        if (element.val() == "") {
            // this handles diffrent message for required fields
            if (this.required[element.attr("id")]) {

                // when msg not empty, it means we are on the current field || this.messages[element.attr("id")]!="" && start_validation==1, so need to display default as field is empty
                if (msg != "") msg = _("This field is required");

                this.fieldFail(element, msg);
                return 1;
            } else {
                this.fieldOk(element);
                return 0;
            }
        } else {
            // this checks regular expression
            if (element.val().match(expression)) {
                if (element.val().match(/^ +$/) && this.required[element.attr("id")]) {
                    this.fieldFail(element, msg);
                    return 1;
                } else {
                    this.fieldOk(element);
                    return 0;
                }
            } else {
                this.fieldFail(element, msg);
                return 1;
            }
        }
    };





    // handles display on correct field
    this.fieldOk = function (element) {
        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {
            element.parent().children("span.error-message").remove();
           // element.next("span").removeClass("fail");
           // element.next("span").addClass("accept");
        }
    };

    // handles display on wrong field	
    this.fieldFail = function (element, msg) {

        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {

            element.parent().children("span.error-message").remove();
          //  element.next("span").removeClass("accept");
           // element.next("span").addClass("fail");
            if (msg == "") {
                element.parent().children("span.error-message").remove();
            } else {

                element.parent().append("<span class=\"error-message\">" + msg + "</span>");
            };
        }
    };


    // validates login field
    var previous_check;
    this.password_field = function (element, expression, length, current, msg) {
        this.currentElement = element;
        this.currentMsg = msg;
        if (element.val() == "") {
            if (msg != "") msg = _("This field is required");
            this.fieldFail(element, msg);
            return 1;
        } else {
            if (element.val().length < length) {
                this.fieldFail(element, _("Bad Password"));
                return 1;
            } else {
                // if current is not login field and was checked before (!=1), we will not run request
                if (current.attr("id") != element.attr("id") && this.passwordCheck > 0) {
                    // value 2 means previously field was validated as ok
                    if (this.passwordCheck == 2) {
                        this.fieldOk(element);
                        return 0;
                    }
                    // value 3 means previously field was validated as false
                    if (this.passwordCheck == 3) {
                        this.fieldFail(element, msg);
                        return 1;
                    }
                }
                this.ajaxRun = true;
                clearTimeout(previous_check);
                previous_check = setTimeout(" uWinAccount.api.checkPasswordE('" + element.val() + "')", 300);

                // always return 0 , additional check in makeCall
                return 0;
            }

        }
    };

    this.compare_repeats = function (field_1, field_2, expression, msg, msg2, length) {
        // check if not empty
        if (field_2.val() != '') {
            // bad format
            if (length != null && field_2.val().length < length) {
                this.fieldFail(field_2, _("Must be at least 6 characters long"));
                return 1;
            } else if (!field_2.val().match(expression)) {
                this.fieldFail(field_2, _("Contains invalid characters"));
                return 1;
                // fields do not match
            } else if (field_1.val() != field_2.val()) {
                this.fieldFail(field_2, _("Passwords does not match"));
                return 1;
                // everything ok
            } else {
                this.fieldOk(field_2);
                return 0;
            }
        } else {
            if (msg != "") msg = _("This field is required");
            this.fieldFail(field_2, msg);
            return 1;
        }
    };



    this.form = function (current) {
        this.errorCount = 0;
        this.ajaxRun = false;
        var mark_check = true;
        // goes through all inputs
        this.inputs.each(function () {
            // if current element, add error message to display, otherwise reset it to empty
            if ($(this).attr("id") == current.attr("id")) {
                msg = self.messages[current.attr("id")];
                self.checked_fields[$(this).attr("id")] = 1;
            } else {
                // if we didn't loop over current (mark_check is still true), than set array element to 1
                if (mark_check) {
                    self.checked_fields[$(this).attr("id")] = 1;
                };
                msg = "";
            };
            switch ($(this).attr("id")) {

            case "new_password_2":
                self.errorCount += self.compare_repeats($("#new_password_1"), $(this), /^[a-zA-Z0-9!.-]{6,20}$/, msg, self.messages["new_password_1"], 6);
                break;
            case "new_password_1":
                self.errorCount += self.standard_field($(this), /^[a-zA-Z0-9!.-]{6,20}$/, msg, 6);
                break;

            case "old_password":
                self.errorCount += self.password_field($(this), /^[a-zA-Z0-9_.-ßäöüÄÖÜ&$*]+$/, 6, current, msg);
                break;
            default:
                break;
            };
            // if loop is on currently checked, than set mark_check to false
            if ($(this).attr("id") == current.attr("id")) {
                mark_check = false;
            };
        });
        this.handleSubmitButton();
    };

    this.handleSubmitButton = function () {
        if (!this.errorCount) {
            if (!this.ajaxRun) {
                document.getElementById("submit").disabled = false;
                $(".submit-button").addClass("green");
				$(".submit-button").attr("style","cursor:pointer;");
                $(".submit-button").parent('p').prev("div.arrow").addClass("arrow-green");
            }
        } else {

            document.getElementById("submit").disabled = true;
            $(".submit-button").removeClass("green");
			$(".submit-button").attr("style","");
            $(".submit-button").parent('p').prev("div.arrow").removeClass("arrow-green");
        }
    };

} (jQuery);


//jarek edit
uWinAccount.EditDetailsValidate = new

function ($) {
    var self = this;
    this.errorCount = 0;
    this.passwordCheck = 0;
    this.ajaxRun;
    this.currentElement;
    this.currentMsg;
    this.required;
    this.messages;
    this.inputs;
    this.checked_fields = Object();

    this.construct = function (required, messages, inputs) {
        this.required = required;
        this.messages = messages;
        this.inputs = inputs;
        this.inputs.each(function () {
            self.checked_fields[$(this).attr("id")] = 0;
        });
    };

    // function that validates on reg exp
    this.standard_field = function (element, expression, msg) {
        // first check if empty
        if (element.val() == "") {
            // this handles diffrent message for required fields
            if (this.required[element.attr("id")]) {

                // when msg not empty, it means we are on the current field || this.messages[element.attr("id")]!="" && start_validation==1, so need to display default as field is empty
                if (msg != "") msg = _("This field is required");

                this.fieldFail(element, msg);
                return 1;
            } else {
                this.fieldOk(element);
                return 0;
            }
        } else {
            // this checks regular expression
            if (element.val().match(expression)) {
                if (element.val().match(/^ +$/) && this.required[element.attr("id")]) {
                    this.fieldFail(element, msg);
                    return 1;
                } else {
                    this.fieldOk(element);
                    return 0;
                }
            } else {
                this.fieldFail(element, msg);
                return 1;
            }
        }
    };



/*

    // handles display on correct field
    this.fieldOk = function (element) {
        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {
            element.parent().children("span.error-message").remove();
       ///     element.next("span").removeClass("fail");
       //     element.next("span").addClass("accept");
        }
    };

    // handles display on wrong field	
    this.fieldFail = function (element, msg) {

        if (!element) element = this.currentElement;
console.log("fail");
console.log(element);
        if (this.checked_fields[element.attr("id")]) {

            element.parent().children("span.error-message").remove();
           // element.next("span").removeClass("accept");
           // element.next("span").addClass("fail");
            if (msg == "") {
                element.parent().children("span.error-message").remove();
            } else {

                element.parent().append("<span class=\"error-message\">" + msg + "</span>");
            };
        }
    };
*/

    // handles display on correct field
    this.fieldOk = function (element,bind_remove) {


        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {
            element.parent("p").removeClass("form-row-error").children("span.error-message").remove();
            element.next("span").removeClass("fail");
            element.next("span").addClass("accept");

        }
    };
    // handles display on wrong field	
    this.fieldFail = function (element, msg,bind_remove) {

        if (!element) element = this.currentElement;

		
		
		if(cur.attr("id")==element.attr("id")) {

if (this.checked_fields[element.attr("id")]) {
            element.next("span").removeClass("accept");
            element.next("span").addClass("fail");
}
            if (msg == "") {
 
            } else {
				if(bind_remove==undefined)
	{
		
	}
if(element.parent("p").find("span.error-message").length>=1) element.parent("p").find("span.error-message").remove();
			
               element.parent("p").addClass("form-row-error").append("<span class=\"error-message\">" + msg + "</span>");
                
                if (element.attr("id") != cur.attr("id")) {
                   
				element.parent("p").removeClass("form-row-error").children("span.error-message").remove();
				   
                } //here if problems
            };
}
        
    };

    // validates login field
    var previous_check;
    this.password_field = function (element, expression, length, current, msg) {
        this.currentElement = element;
        this.currentMsg = msg;
        if (element.val() == "") {
            if (msg != "") msg = _("This field is required");
            this.fieldFail(element, msg);
            return 1;
        } else {
            if (element.val().length < length) {
                this.fieldFail(element, _("Bad Password"));
                return 1;
            } else {
                // if current is not login field and was checked before (!=1), we will not run request
                if (current.attr("id") != element.attr("id") && this.passwordCheck > 0) {
                    // value 2 means previously field was validated as ok
                    if (this.passwordCheck == 2) {
                        this.fieldOk(element);
                        return 0;
                    }
                    // value 3 means previously field was validated as false
                    if (this.passwordCheck == 3) {
                        this.fieldFail(element, msg);
                        return 1;
                    }
                }
                this.ajaxRun = true;
                clearTimeout(previous_check);
                previous_check = setTimeout(" uWinAccount.api.checkPasswordG('" + element.val() + "')", 300);

                // always return 0 , additional check in makeCall
                return 0;
            }

        }
    };



//szf
var cur;
    this.form = function (current) {
        this.errorCount = 0;
        this.ajaxRun = false;
cur=current;
        var mark_check = true;
        // goes through all inputs
        this.inputs.each(function () {
            // if current element, add error message to display, otherwise reset it to empty
            if ($(this).attr("id") == current.attr("id")) {
                msg = self.messages[current.attr("id")];
                self.checked_fields[$(this).attr("id")] = 1;
            } else {
                // if we didn't loop over current (mark_check is still true), than set array element to 1
                if (mark_check) {
                    self.checked_fields[$(this).attr("id")] = 1;
                };
                msg = "";
            };
            switch ($(this).attr("id")) {

            case "PrimaryEmail":
                self.errorCount += self.standard_field($(this), /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/, msg);
                break;
            case "HomePhone":
            case "MobilePhone":
                self.errorCount += self.standard_field($(this), /^[0-9]+$/, msg);
                break;
            case "StreetAddress":

                self.errorCount += self.standard_field($(this), /^[\d\D]+$/, msg);
                break;
            case "City":
            case "CountyOrStateOrProvince":


                self.errorCount += self.standard_field($(this), /^[\d\D]+$/, msg);
                break;
            case "password_edit_details":
                self.errorCount += self.password_field($(this), /^[a-zA-Z0-9_.-ßäöüÄÖÜ&$*]+$/, 6, current, msg);
                break;
            case "PostCode":
                self.errorCount += self.standard_field($(this), /^[\d\D]+$/, msg);
                break;
            default:
                break;
            };
            // if loop is on currently checked, than set mark_check to false
            if ($(this).attr("id") == current.attr("id")) {
                mark_check = false;
            };
        });
        this.handleSubmitButton();
    };

    this.handleSubmitButton = function () {
        if (!this.errorCount) {
            if (!this.ajaxRun) {
                document.getElementById("submit").disabled = false;
                $(".submit-button").addClass("green");
				$(".submit-button").attr("style","cursor:pointer;");
                $(".submit-button").parent('p').prev("div.arrow").addClass("arrow-green");
            }
        } else {

            document.getElementById("submit").disabled = true;
            $(".submit-button").removeClass("green");
			$(".submit-button").attr("style","");
            $(".submit-button").parent('p').prev("div.arrow").removeClass("arrow-green");
        }
    };

} (jQuery);

//
// ============================ BetSlip UI layer ============================ //
uWinAccount.ui = new

function ($) {
    // this is run first to set everything up
    // setup the necessary functions
    // called when an error occurs
    this.error = function (message) {
        alert(message);
    };

    // this.login - call this when the user logs in
    this.login = function () {
        // update something to say logged in
        // maybe pop up a box
        alert("you have been logged in");
    };

    var vget = function (name) {
  	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  	  var regexS = "[\\?&]"+name+"=([^&#]*)";
  	  var regex = new RegExp( regexS );
  	  var results = regex.exec( window.location.href );
  	  if( results == null ) {
  	    return "";
  	  } else {
  	    return results[1];    	
  	  } 
    };    

    this.GetTransaction = function (pid, box, buttonText) {
		var orgButtonText = (typeof(buttonText)!='undefined') ? buttonText : false;
		if (typeof(pid) == 'object' && typeof(pid.WCFApplicationException)!='undefined') {
			$(box).html('<p style="display: block; text-align: center">'+pid.WCFApplicationException.Message+'<br/></p>');
			if ($('#deposit-page-next-cc').html() || $('#withdraw-page-cc').html() || $('#withdraw-page-nt').html() || $('#deposit-page-neteller').html()) {								
				if ($('#deposit-amount').html()) {
					$('#deposit-amount').removeAttr('readonly');
				}
				if ($('#withdraw-amount').html()) {
					$('#withdraw-amount').removeAttr('readonly');
				}
				$('#password-value').removeAttr('readonly');
				if ($('#cv2').html()) {
					$('#cv2').removeAttr('readonly');
				}
				if (orgButtonText!=false) {
					$('div.form-row-submit button:first').html(orgButtonText);	
				}
			}	
			return false;
		}
		
		var trans = uWinAccount.api.GetPaymentTransaction (pid);
		if (typeof(trans) == 'undefined') {
				$(box).html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+' <br/>'+trans.Description+' '+(trans.ExtAdditionalData || '')+'</p>');
				if ($('#deposit-page-next-cc').html() || $('#withdraw-page-cc').html() || $('#withdraw-page-nt').html() || $('#deposit-page-neteller').html()) {								
					if ($('#deposit-amount').html()) {
						$('#deposit-amount').removeAttr('readonly');
					}
					if ($('#withdraw-amount').html()) {
						$('#withdraw-amount').removeAttr('readonly');
					}
					$('#password-value').removeAttr('readonly');
					if ($('#cv2').html()) {
						$('#cv2').removeAttr('readonly');
					}
					if (orgButtonText!=false) {
						$('div.form-row-submit button:first').html(orgButtonText);	
					}
				}	
				return false;
		} else if (typeof(trans) == 'object' && typeof(trans.WCFApplicationException)!='undefined') {
				$(box).html('<p style="display: block; text-align: center">'+trans.WCFApplicationException.Message+' <br/>'+trans.Description+'</p>');
				if ($('#deposit-page-next-cc') || $('#withdraw-page-cc') || $('#withdraw-page-nt') || $('#deposit-page-neteller')) {								
					if ($('#deposit-amount').html()) {
						$('#deposit-amount').removeAttr('readonly');
					}
					if ($('#withdraw-amount').html()) {
						$('#withdraw-amount').removeAttr('readonly');
					}
					$('#password-value').removeAttr('readonly');
					if ($('#cv2')) {
						$('#cv2').removeAttr('readonly');
					}
					if (orgButtonText!=false) {
						$('div.form-row-submit button:first').html(orgButtonText);	
					}
				}	
				return false;
		} else {
			
			switch (trans.IDMMSITransactionState) {
				case "Q":
					//withdraw complete
					$(box).html('<p style="display: block; text-align: center">'+_("Your withdrawal has been sent for authorisation.")+'</p>');
					if ($('#withdraw-page-cc').html()) {								
						$('#withdraw-page-cc').slideToggle();
					}
					if ($('#withdraw-page-mb').html()) {								
						$('#withdraw-page-mb').slideToggle();
					}
					if ($('#withdraw-page-nt').html()) {								
						$('#withdraw-page-nt').slideToggle();
					}
					return true;
					break;
				case "X":
				case "M":
				case "H":
					// transaction complete
			        var details = uWinAccount.api.GetPersonalDetails();
					$(box).html('<p style="display: block; text-align: center">'+_("Deposit complete.")+'</p>');
					var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
					var lang = 'en';

					if (document.cookie.length>0) {
						c_start=document.cookie.indexOf ("lang=");
						if (c_start!=-1) {
							c_start=c_start + 5;
							c_end=document.cookie.indexOf (";",c_start);
							if (c_end==-1) c_end=document.cookie.length;
							lang = unescape(document.cookie.substring(c_start,c_end));
					    }
					}
					lang = lang.toLowerCase();
					if ($('#deposit-page-next-cc').html()) {								
						$('#deposit-page-next-cc').slideToggle();
						$(box).append('<img src="https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl=' + url + '/deposit-confirm&language='+lang+'&deposit_confirm=confirm&deposit_val='+$('#deposit-amount').val()+'&deposit_type=credit-card" width="1" height="1"/>');
						if (typeof(details)!='undefined' && typeof(details.UserName)!='undefined') {
							$(box).append('<iframe src="https://ee.connextra.com/universalTag?client=YouWin&id=177829&page=depositconfirm&ac='+details.UserName+'&val='+$('#deposit-amount').val()+'" width="0" height="0" scrolling="no" frameborder="0" style="border-width:0"></iframe>');
						}
					} else if ($('#deposit-page-neteller').html()) {								
						$('#deposit-page-neteller').slideToggle();
						$(box).append('<img src="https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl=' + url + '/deposit-confirm&language='+lang+'&deposit_confirm=confirm&deposit_val='+$('#deposit-amount').val()+'&deposit_type=neteller" width="1" height="1"/>');
						if (typeof(details)!='undefined' && typeof(details.UserName)!='undefined') {
							$(box).append('<iframe src="https://ee.connextra.com/universalTag?client=YouWin&id=177829&page=depositconfirm&ac='+details.UserName+'&val='+$('#deposit-amount').val()+'" width="0" height="0" scrolling="no" frameborder="0" style="border-width:0"></iframe>');
						}
					}
					uWinAccount.api.UpdateBalanceOnTop();
					return true;
					break;
				case "F":
				case "E":
				case "D":
				case "R":
				case "L":
				case "C":
				case "J":
					// transaction failed
					$(box).html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+' <br/>'+trans.Description+' '+(trans.ExtAdditionalData || '')+'</p>');
					if ($('#deposit-page-next-cc') || $('#withdraw-page-cc') || $('#withdraw-page-nt') || $('#deposit-page-neteller')) {								
						if ($('#deposit-amount').html()) {
							$('#deposit-amount').removeAttr('readonly');
						}
						if ($('#withdraw-amount').html()) {
							$('#withdraw-amount').removeAttr('readonly');
						}
						$('#password-value').removeAttr('readonly');
						if ($('#cv2')) {
							$('#cv2').removeAttr('readonly');
						}
						if (orgButtonText!=false) {
							var oldVal = $('div.form-row-submit button:first').html();
							$('div.form-row-submit button:first').html(orgButtonText);	
						}
					}	
					return false;
					break;
				case "A":
				case "S":
				case "N":
				case "K":
				case "G":
				case "V":
				case "T":
					// wait 3s
					redirectionObject = function () {
						uWinAccount.ui.GetTransaction (pid, box, buttonText);
					}	
					setTimeout("redirectionObject()", 3000);	
					break;
				case "W":
					// ready for redirection
					$(box).html('<p style="display: block; text-align: center"><img src="./?a=4290"/>'+trans.Description+'</p>');
					var params = {
						'Description': 		"Deposit for youwin",
						'IDMMSITXRequest':	trans.IDMMSITXRequest,
						'LanguageCode':		"GB",
						'ReturnUrl':		window.location.href.split('?')[0]+'?completed=1'
					};
					uWinAccount.api.StoreMoneybookersDeposit ('moneybookersDeposit', $('#deposit-amount').val());
					var redirection = uWinAccount.api.GetRBWRequest(params);
					if (typeof (redirection) != 'undefined') {
						$('#amount-box').hide();
						$('#password-box').hide();
						$('#moneybookers-email').hide();
						var url = redirection.UrlWithParameters;
						url=url.replace(/'/,"%27");
						var parts = url.split('&');
						for (var i=0;i<parts.length;i++) {
							if (parts[i].indexOf('=')>0) {
								if (parts[i].split('=')[0]=='pay_from_email') {
									if ($('#moneybookers-from-email').val()!='') {
										parts[i]='pay_from_email='+$('#moneybookers-from-email').val();
									} 	
								}	
								if (parts[i].split('=')[0]=='language') {
									var lang = 'GB';

									if (document.cookie.length>0) {
										c_start=document.cookie.indexOf ("lang=");
										if (c_start!=-1) {
											c_start=c_start + 5;
											c_end=document.cookie.indexOf (";",c_start);
											if (c_end==-1) c_end=document.cookie.length;
											lang = unescape(document.cookie.substring(c_start,c_end));
									    }
									}
									parts[i]='language='+lang;
								}	
								if (parts[i].split('=')[0]=='status_url') {
									parts[i]='status_url=http%3a%2f%2f217.168.160.114%2f_api-scripts%2fwww%2fmoneybookers%2fprocess.php';
								}	
							}	
							
						}	
						url = parts.join('&');
						if ($('#deposit-page-next')) {
							var html = '<div style="text-align: center">'+_("Clicking the button below will take you to the Moneybookers site where you can finish the deposit process.")+'</div><div class="form-row-submit"><button style="margin-left: 232px;" class="reg-btn-create-account" onclick="window.location=\''+url+'&merchant_fields=field1&field1='+trans.IDMMSITXRequest+'\'">'+_("Go to moneybookers")+'</button></div>';
							$('#deposit-page-next').slideToggle();
						} else {
							var html = '<div style="text-align: center"><br/>'+_("Clicking the button below will take you to the Moneybookers site where you can finish the deposit process.")+'<br/><input type="submit" class="long_button" value="'+_("Go to moneybookers")+'" onclick="window.location=\''+url+'&merchant_fields=field1&field1='+trans.IDMMSITXRequest+'\'"/></div>';
						}
						$(box).html(html);
					} else {
						$(box).html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+' <br/>'+trans.Description+' '+(trans.ExtAdditionalData || '')+'</p>');
					}	
					return true;
					break;
			}
		}	

    	
    	
    };
    
    this.MakeDeposit = function () {
    	uWinAccount.ui.MakePayment('R');
    }

    this.MakeWithdraw = function () {
    	uWinAccount.ui.MakePayment('P');
    }
    
    this.MakePayment = function (mode) {
    	if (vget("instruction")!="" && vget("type")!="") {
    		var payment = uWinAccount.api.GetPaymentInstrument (vget("instruction"));
    		if (typeof(payment) != 'undefined' && payment!=false) {
    			switch (payment.IDMMSIType) {
    				case 'VE':
    				case 'VC':
    				case 'DE':
    				case 'MC':
    				case 'MA':
    				case 'SL':
    				case 'SLO':
    					//use cvv call
						var orgButtonText = $('div.form-row-submit button:first').html();
    					if (mode == 'R') {
   							var amount = $('#deposit-amount').val();
   							var instruction = vget("instruction");
   							var password = $('#password-value').val()
  							var cv2 = $('#cv2').val()
   							$('#deposit-amount').attr('readonly','readonly');
   							$('#cv2').attr('readonly','readonly');
   							$('#password-value').attr('readonly','readonly');
							$('div.form-row-submit button:first').html('<img src="./?a=4290"/> '+_('Processing...'));
							$('#transaction-status').show();
							$('#status-box').html('<p style="display: block; text-align: center"><img src="./?a=4290"/> '+_("Please wait, processing transaction...")+'</p>');
   							var pid = uWinAccount.api.BeginPaymentTransactionWithSecurityCode (mode, instruction, amount, cv2, password);
    					} else {
   							var amount = $('#withdraw-amount').val();
   							var instruction = vget("instruction");
   							var password = $('#password-value').val()
  							var cv2 = $('#cv2').val()
   							$('#withdraw-amount').attr('readonly','readonly');
   							$('#cv2').attr('readonly','readonly');
   							$('#password-value').attr('readonly','readonly');
							$('div.form-row-submit button:first').html('<img src="./?a=4290"/> '+_('Processing...'));
							$('#transaction-status').show();
							$('#status-box').html('<p style="display: block; text-align: center"><img src="./?a=4290"/> '+_("Please wait, processing transaction...")+'</p>');
    						var pid = uWinAccount.api.BeginPaymentTransactionWithSecurityCode (mode, instruction, amount, cv2, password);
    					}	
    					if (pid == false) {
							if ($('#deposit-amount').html()) {
   								$('#deposit-amount').removeAttr('readonly');
							}
							if ($('#withdraw-amount').html()) {
   								$('#withdraw-amount').removeAttr('readonly');
							}
   							$('#password-value').removeAttr('readonly');
   							$('#cv2').removeAttr('readonly');
							$('div.form-row-submit button:first').html(orgButtonText);
    						$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction. Check your password")+'</p>');
						} else if (typeof(pid) == 'object' && typeof(pid.WCFApplicationException)!='undefined') {
							if ($('#deposit-amount').html()) {
   								$('#deposit-amount').removeAttr('readonly');
							}
							if ($('#withdraw-amount').html()) {
   								$('#withdraw-amount').removeAttr('readonly');
							}
							$('#password-value').removeAttr('readonly');
							$('#cv2').removeAttr('readonly');
							$('div.form-row-submit button:first').html(orgButtonText);						
							$('#status-box').html('<p style="display: block; text-align: center">'+pid.WCFApplicationException.Message+'<br/></p>');
    					} else {
    						//get transaction state
    						var ret = uWinAccount.ui.GetTransaction (pid, $('#status-box'), orgButtonText);
    					}	

    					break;
					case 'NT':
						var orgButtonText = $('div.form-row-submit button:first').html();
						if (mode=='R') {
    							var amount = $('#deposit-amount').val();
    							var instruction = vget("instruction");
    							var password = $('#password-value').val()
    							$('#deposit-amount').attr('readonly','readonly');
    							$('#password-value').attr('readonly','readonly');
								$('div.form-row-submit button:first').html('<img src="./?a=4290"/> '+_('Processing...'));
								$('#transaction-status').show();

    							var pid = uWinAccount.api.BeginPaymentTransaction(mode, instruction, amount, password);
        						if (pid == false) {
	    							$('#deposit-amount').removeAttr('readonly');
	    							$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
            						$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction. Deposit failed.")+'</p>');
								} else 	if (typeof(pid) == 'object') {
		    						$('#deposit-amount').removeAttr('readonly');
		    						$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
		        					$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+' '+(pid.WCFApplicationException.Message || '')+'</p>');
        						} else {
        							uWinAccount.ui.GetTransaction(pid, $('#status-box'), orgButtonText);
        						}
						} else {
								var amount = $('#withdraw-amount').val();
    							var instruction = vget("instruction");
    							var password = $('#password-value').val()
    							$('#withdraw-amount').attr('readonly','readonly');
    							$('#password-value').attr('readonly','readonly');
								$('div.form-row-submit button:first').html('<img src="./?a=4290"/> '+_('Processing...'));
								$('#transaction-status').show();
    							var pid = uWinAccount.api.BeginPaymentTransaction(mode, instruction, amount, password);
    							if (typeof(pid) == 'object') {
	    							$('#withdraw-amount').removeAttr('readonly');
	    							$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
	        						$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+' '+(pid.WCFApplicationException.Message || '')+'</p>');
    							} else if (pid == false) {
   	    							$('#withdraw-amount').removeAttr('readonly');
	    							$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
         							$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+'</p>');
        						} else {
        							uWinAccount.ui.GetTransaction(pid, $('#status-box'), orgButtonText);
        						}
						}
						break;
    				case 'Moneybookers':
						var orgButtonText = $('div.form-row-submit button:first').html();
    					if (mode == 'R') {
							if ($('#deposit-page-next').html()) {
    							var amount = $('#deposit-amount').val();
    							var instruction = vget("instruction");
    							var password = $('#password-value').val()
    							$('#deposit-amount').attr('readonly','readonly');
    							$('#password-value').attr('readonly','readonly');
								$('div.form-row-submit button:first').html('<img src="./?a=4290"/> '+_('Processing...'));
								$('#transaction-status').show();

    							var pid = uWinAccount.api.BeginPaymentTransaction(mode, instruction, amount, password);
        						if (pid == false) {
	    							$('#deposit-amount').removeAttr('readonly');
	    							$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
            						$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction. Deposit failed.")+'</p>');
        						} else {
        							uWinAccount.ui.GetTransaction(pid, $('#status-box'), orgButtonText);
        						}
							} 
    					} else {
							if ($('#withdraw-page-mb').html()) {
								var amount = $('#withdraw-amount').val();
    							var instruction = vget("instruction");
    							var password = $('#password-value').val()
    							$('#withdraw-amount').attr('readonly','readonly');
    							$('#password-value').attr('readonly','readonly');
								$('div.form-row-submit button:first').html('<img src="./?a=4290"/> '+_('Processing...'));
								$('#transaction-status').show();
    							var pid = uWinAccount.api.BeginPaymentTransaction(mode, instruction, amount, password);
    							if (typeof(pid) == 'object') {
	    							$('#withdraw-amount').removeAttr('readonly');
	    							$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
	        						$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+' '+(pid.WCFApplicationException.Message || '')+'</p>');
    							} else if (pid == false) {
   	    							$('#withdraw-amount').removeAttr('readonly');
	    							$('#password-value').removeAttr('readonly');
									$('div.form-row-submit button:first').html(orgButtonText);
         							$('#status-box').html('<p style="display: block; text-align: center">'+_("There was an error processing the transaction.")+'</p>');
        						} else {
        							uWinAccount.ui.GetTransaction(pid, $('#status-box'), orgButtonText);
        						}	
							}
    					}	
    					break;
    			}
    			
    		} else {
        		$('#deposit-page').hide();
    		}	
    	} else {
    		$('#deposit-page').hide();
    	}
    }	

    // this function will run when the page is ready for JavaScript
    $(function () {
        // pageready code here

    });
} (jQuery);

// ============================ Site interaction layer ============================ //
uWinAccount.site = new

function ($) {
    // this is run first to set everything up
    var site = this;
    var account;
    // setup the necessary functions
    //o tutaj
    //Start Edit Details

    var vget = function (name) {
    	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    	  var regexS = "[\\?&]"+name+"=([^&#]*)";
    	  var regex = new RegExp( regexS );
    	  var results = regex.exec( window.location.href );
    	  if( results == null ) {
    	    return "";
    	  } else {
    	    return results[1];    	
    	  } 
    }	
    // this function will run when the page is ready for JavaScript
    $(function () {

    	uWinAccount.api.check_logging();
        if ($("#edit-details").html() != null) {
            uWinAccount.api.checkLoggedIn("#content");
            uWinAccount.api.FillInPersonalDetailsInEditDetails();
            required_1 = {
                'StreetAddress': 1,
                'HomePhone': 1,
                'MobilePhone': 0,
                'PrimaryEmail': 1,
                'City': 1,
                'password_edit_details': 1
            };
            messages_1 = {
                'StreetAddress': _("Contains invalid characters"),
                'HomePhone': _("Contains invalid characters"),
                'PrimaryEmail': _("Contains invalid characters"),
                'City': _("Contains invalid characters"),
                'CountyOrStateOrProvince': _("Contains invalid characters"),
                'PostCode': _("Contains invalid characters"),
                'password_edit_details': _("Bad Password")

            };
            // disable next step button
            document.getElementById("submit").disabled = true;
            // get all form inputs except hiddens
            var inputs = $("input[type!='hidden'],select");

            uWinAccount.EditDetailsValidate.construct(required_1, messages_1, inputs);
            $("#submit").click(function (event) {
                event.preventDefault();
                uWinAccount.api.EditDetails();
            });
            // apply events to inputs and selects
            $("#edit-details input[type!='checkbox']").each(function () {
                $(this).bind("blur keyup", function () {
                    uWinAccount.EditDetailsValidate.form($(this));
                });
            });
        }
        //Successful deposit
        else if ($('#deposit-success').html() != null) {
			var data = uWinAccount.api.GetDepositSuccessData();
			var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
			var lang = 'en';

			if (document.cookie.length>0) {
				c_start=document.cookie.indexOf ("lang=");
				if (c_start!=-1) {
					c_start=c_start + 5;
					c_end=document.cookie.indexOf (";",c_start);
					if (c_end==-1) c_end=document.cookie.length;
					lang = unescape(document.cookie.substring(c_start,c_end));
			    }
			}
			lang = lang.toLowerCase();
			$('#record').html('<img src="https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl=' + url + '/deposit-confirm&language='+lang+'&deposit_confirm=confirm&deposit_val='+data.amount+'&deposit_type=credit-card" width="1" height="1"/>');
			uWinAccount.api.UpdateBalanceOnTop();
        }
        //Failed deposit
        else if ($('#deposit-failure').html() != null) {
			var data = uWinAccount.api.GetDepositFailureData();
			$('#record').html(data);
        }
		//Register card and deposit
        else if ($('#card-register-deposit').html() != null) {
        	var details = uWinAccount.api.GetPersonalDetails();

        	if (details && typeof(details.StreetAddress)!='undefined') {
				$('#card-register-deposit input[name=NameAsOnCard]').val(details.FullName.replace(/  /, ' '));
				$('#card-register-deposit input[name=Email]').val(details.PrimaryEmail);
				var showAdd = false;
				
				if (!details.StreetAddress) {
					showAdd = true;	
				} else {
					$('#card-register-deposit input[name=Address]').val(details.StreetAddress.replace("\n","").replace("\r","")).attr('disabled', true);
				}
				if (!details.PostCode) {
					showAdd = true;	
				} else {
					$('#card-register-deposit input[name=Postcode]').val (details.PostCode).attr('disabled', true);
				}
				if (!details.City) {
					showAdd = true;	
				} else {
					$('#card-register-deposit input[name=City]').val (details.City).attr('disabled', true);
				}	
				$('#card-register-deposit input[name=State]').val (details.CountyOrStateOrProvince);
				if (!details.IDMMCountry) {
					showAdd = true;	
				} else {
					$('#card-register-deposit select[name=Country]').val (details.IDMMCountry.toLowerCase()).attr('disabled', true);
				}
				
				if (showAdd) {
					$('#cc-address').slideToggle();
				}
					
        		$('#card-register-deposit button:first').click(function () {
					var proceed = true;
					
					$('#card-register-deposit .req').each(function (i) {
						if ($(this).val() == '') {
							$(this).css('background-color','#ff8888');
							proceed = false;
						} else {
							$(this).css('background-color','white');
						}
					});
					
					if (proceed) {
						var orgButtonText = $('#card-register-deposit button:first').html();
						$('#card-register-deposit button:first').css('margin','32px 0 25px 233px');
						if ($('#redhint').html()!=null) {
							$('#redhint').remove();
						}
	        			$('#card-register-deposit button:first').html('<img src="./?a=4290"/> '+_("Processing..."));	                
	        			var details = {
							Email:          		($('#card-register-deposit input[name=Email]').val() || ''),
							NameAsOnCard: 			($('#card-register-deposit input[name=NameAsOnCard]').val() || ''),
							CardNumber:	 			($('#card-register-deposit input[name=CardNumber]').val () || ''),
							CardCV2:	 			($('#card-register-deposit input[name=CardCV2]').val () || ''),
							ExpireMonth: 			($('#card-register-deposit select[name=EndOfValidityMonth]').val () || ''),
							ExpireYear: 			($('#card-register-deposit select[name=EndOfValidityYear]').val () || ''),
							Amount: 				($('#card-register-deposit input[name=Amount]').val () || ''),
							CardType: 				($('#card-register-deposit select[name=CardType]').val () || ''),
							Address:          		($('#card-register-deposit input[name=Address]').val() || ''),
							City:          			($('#card-register-deposit input[name=City]').val() || ''),
							State:          		($('#card-register-deposit input[name=State]').val() || ''),
							PostCode:          		($('#card-register-deposit input[name=Postcode]').val() || ''),
							Country:          		($('#card-register-deposit select[name=Country]').val() || ''),
							CardIssueNumber: 		($('#card-register-deposit input[name=CardIssueNumber]').val () || '')
	        			};
	
						$('#transaction-status').show();
						if (vget("instruction")!="") {
	        				var response = uWinAccount.api.RegisterCardAndDeposit (details, false);
						} else {
	        				var response = uWinAccount.api.RegisterCardAndDeposit (details, true);
						}
								
	        			if (typeof (response) == 'number' || typeof (response) == 'string') {
							$('#card-add').slideToggle();	                
							var html = '<div style="text-align: center">'+_("Deposit complete. Thank you.")+'</div>';
					        var details = uWinAccount.api.GetPersonalDetails();
							var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
							var lang = 'en';

							if (document.cookie.length>0) {
								c_start=document.cookie.indexOf ("lang=");
								if (c_start!=-1) {
									c_start=c_start + 5;
									c_end=document.cookie.indexOf (";",c_start);
									if (c_end==-1) c_end=document.cookie.length;
									lang = unescape(document.cookie.substring(c_start,c_end));
							    }
							}

							$('#status-box').html(html);
							$('#status-box').append('<img src="https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl=' + url + '/deposit-confirm&language='+lang+'&deposit_confirm=confirm&deposit_val='+$('#card-register-deposit input[name=Amount]').val()+'&deposit_type=credit-card" width="1" height="1"/>');
							if (typeof(details)!='undefined' && typeof(details.UserName)!='undefined') {
								$('#status-box').append('<iframe src="https://ee.connextra.com/universalTag?client=YouWin&id=177829&page=depositconfirm&ac='+details.UserName+'&val='+$('#card-register-deposit input[name=Amount]').val()+'" width="0" height="0" scrolling="no" frameborder="0" style="border-width:0"></iframe>');
							}
							uWinAccount.api.UpdateBalanceOnTop();	
			           	} else if (typeof (response) == 'object' && typeof (response.message) == 'undefined') {
							$('#card-register-deposit button:first').html(orgButtonText);
							$('html, body').animate({scrollTop: $('#card-register-deposit button:first').offset().top}, 'slow');
							if (typeof (response.WCFApplicationException) != 'undefined') {
								$('#status-box').html('<div style="text-align: center">'+response.WCFApplicationException.Message+'</div>');	                
							}	
						} else if (typeof (response.message) != 'undefined' && response.message=='3D') {
							$('#card-add').slideToggle();	                
							var url = window.location.href.replace(/register-card-and-deposit/,'register-card-and-deposit/?status=S3D');
							var html = '<div id="3ds" style="display: none"><iframe name="3dsframe" id="3dsframe" src="https://www.youwin.com/_api-scripts/www/blank.php" frameborder="0" border="0" width="745" height="400" style="border 1px solid #dddddd"></iframe></div><div id="3dsform"><div style="text-align: center">'+_("Click the button below to perform a Secure 3D authorization with your bank.")+'</div>';
							html+='<form action="'+response.redirect_url+'" method="POST" id="3D" target="3dsframe">';
							html+='<input type="hidden" name="PaReq" value="'+response.PaReq+'"/>';
							html+='<input type="hidden" name="MD" value="'+response.MD+'"/>';
							html+='<input type="hidden" name="TermUrl" value="'+response.termUrl+'"/>';
							html+='<div class="form-row-submit"><button style="margin-left: 232px;" class="reg-btn-create-account" onclick="$(\'#3ds\').slideToggle(\'\', function () {$(\'#3dsform\').hide(); window.setTimeout(function () {$(\'#3D\').submit()}, 2000)});">'+_("Perform 3D authorization")+'</button></div></form></div>';
							$('#status-box').html(html);
						} else if (typeof (response.message) != 'undefined') {
							$('#card-register-deposit button:first').html(orgButtonText);
							$('#card-register-deposit button:first').css('margin','32px 0 5px 233px');
							$('#card-register-deposit button:first').after('<div id="redhint" style="color: red; font-size: 10px; text-align: center; margin-bottom: 25px">'+_('There was a problem proccessing your transaction. Check the status below for more information.')+'</div>');
							$('html, body').animate({scrollTop: $('#card-register-deposit button:first').offset().top}, 'slow');
							$('#status-box').html('<div style="text-align: center">'+response.message+'</div>');	                
						}	
					} else {
						alert(_('Please fill the required fields'));
					}

        		});
        	}	
        	
        }
        //Register card
        else if ($('#card-register').html() != null) {
        	var details = uWinAccount.api.GetPersonalDetails();

        	if (details && typeof(details.StreetAddress)!='undefined') {
				$('#card-register input[name=NameAsOnCard]').val(details.FullName);
				$('#card-register input[name=Email]').val(details.PrimaryEmail);
				var showAdd = false;
				
				if (!details.StreetAddress) {
					showAdd = true;	
				} else {
					$('#card-register input[name=Address]').val(details.StreetAddress.replace("\n","").replace("\r","")).attr('disabled', true);
				}
				if (!details.PostCode) {
					showAdd = true;	
				} else {
					$('#card-register input[name=Postcode]').val (details.PostCode).attr('disabled', true);
				}
				if (!details.City) {
					showAdd = true;	
				} else {
					$('#card-register input[name=City]').val (details.City).attr('disabled', true);
				}	
				$('#card-register input[name=State]').val (details.CountyOrStateOrProvince);
				if (!details.IDMMCountry) {
					showAdd = true;	
				} else {
					$('#card-register select[name=Country]').val (details.IDMMCountry.toLowerCase()).attr('disabled', true);
				}
				
				if (showAdd) {
					$('#cc-address').slideToggle();
				}
					
        		$('#card-register button:first').click(function () {
					var proceed = true;
					
					$('#card-register .req').each(function (i) {
						if ($(this).val() == '') {
							$(this).css('background-color','#ff8888');
							proceed = false;
						} else {
							$(this).css('background-color','white');
						}
					});
					
					if (proceed) {
						var orgButtonText = $('#card-register button:first').html();
	        			$('#card-register button:first').html('<img src="./?a=4290"/> '+_("Processing..."));	                
	        			var details = {
							Email:          		($('#card-register input[name=Email]').val() || ''),
							NameAsOnCard: 			($('#card-register input[name=NameAsOnCard]').val() || ''),
							CardNumber:	 			($('#card-register input[name=CardNumber]').val () || ''),
							CardCV2:	 			($('#card-register input[name=CardCV2]').val () || ''),
							ExpireMonth: 			($('#card-register select[name=EndOfValidityMonth]').val () || ''),
							ExpireYear: 			($('#card-register select[name=EndOfValidityYear]').val () || ''),
							CardType: 				($('#card-register select[name=CardType]').val () || ''),
							Address:          		($('#card-register input[name=Address]').val() || ''),
							City:          			($('#card-register input[name=City]').val() || ''),
							State:          		($('#card-register input[name=State]').val() || ''),
							PostCode:          		($('#card-register input[name=Postcode]').val() || ''),
							Country:          		($('#card-register select[name=Country]').val() || ''),
							CardIssueNumber: 		($('#card-register input[name=CardIssueNumber]').val () || '')
	        			};
	
						$('#transaction-status').show();
	        			var response = uWinAccount.api.RegisterCard (details);

	        			if (typeof (response) == 'number' || typeof (response) == 'string') {
							$('#card-add').slideToggle();	                
							var url = window.location.href.replace(/add-new-card/,'credit-card-deposit');
							var html = '<div style="text-align: center">'+_("Credit card registration successful, you can now proceed to deposit page.")+'</div><div class="form-row-submit"><button style="margin-left: 232px;" class="reg-btn-create-account" onclick="window.location=\''+url+'?instruction='+response+'&type=DE\'">'+_("Make deposit")+'</button></div>';
							$('#status-box').html(html);
			           	} else if (typeof (response) == 'object' && typeof (response.message) == 'undefined') {
							if (typeof (response.WCFApplicationException) != 'undefined') {
								$('#status-box').html(response.WCFApplicationException.Message);	                
							}	
						} else if (typeof (response.message) != 'undefined') {
							$('#card-register button:first').html(orgButtonText);	                
							$('#status-box').html(response.message);	                
						}	
					} else {
						alert(_('Please fill the required fields'));
					}

        		});
        	}	
        	
        }	
        //Register neteller
        else if ($('#neteller-register').html() != null) {
        		$('#neteller-register button:first').click(function () {
					var proceed = true;
					
					$('#neteller-register .req').each(function (i) {
						if ($(this).val() == '') {
							$(this).css('background-color','#ff8888');
							proceed = false;
						} else {
							$(this).css('background-color','white');
						}
					});
					
					if (proceed) {
						var orgButtonText = $('#neteller-register button:first').html();
	        			$('#neteller-register button:first').html('<img src="./?a=4290"/> '+_("Processing..."));	                
	        			var details = {
							Account: 	($('#neteller-register input[name=neteller-account]').val() || ''),
							Pin: 		($('#neteller-register input[name=pin-code]').val() || '')
	        			};
	
						$('#transaction-status').show();
	        			var response = uWinAccount.api.NetellerRegister (details);

						if (response==null) {
							$('#neteller-register button:first').html(orgButtonText);	                
							$('#status-box').html('<div style="text-align: center">'+_("There was an error registering your Neteller account. Please check the numbers you've entered")+'</div>');	                
						} else if (typeof (response) == 'number' || typeof (response) == 'string') {
							$('#neteller-add').slideToggle();	                
							var url = window.location.href.replace(/neteller-registration/,'neteller-deposit');
							var html = '<div style="text-align: center">'+_("Neteller registration successful, you can now proceed to deposit page.")+'</div><div class="form-row-submit"><button style="margin-left: 232px;" class="reg-btn-create-account" onclick="window.location=\''+url+'?instruction='+response+'&type=NT\'">'+_("Make deposit")+'</button></div>';
							$('#status-box').html(html);
						} else if (typeof (response) == 'object' && typeof (response.message) == 'undefined') {
							if (typeof (response.WCFApplicationException) != 'undefined') {
								$('#status-box').html(response.WCFApplicationException.Message);	                
							}	
						} else if (typeof (response.message) != 'undefined') {
							$('#neteller-register button:first').html(orgButtonText);	                
							$('#status-box').html(response.message);	                
						}	
					} else {
						alert(_('Please fill the required fields'));
					}

        		});
        }
		  else if ($("#address-content textarea").val() != null) {
	        	var details = uWinAccount.api.GetPersonalDetails();

	        	if (details) {
	        	//	var address = '<p>'+details.StreetAddress+'</p>';
	        	//	address += '<p>'+details.City+'</p>';
	        	//	address += '<p>'+details.PostCode+'</p>';
	        	//	address += '<p>'+(details.CountyOrState || '')+'</p>';
	        	//	$('#address-content p:first').html(address);
						$("#address-content textarea").val(details.StreetAddress);
							$("#address-content input[name=City]").val(details.City);
								$("#address-content input[name=State]").val(details.CountyOrStateOrProvince || '');
									$("#address-content input[name=PhoneNumber]").val(details.HomePhone);
										$("#address-content input[name=Postcode]").val(details.PostCode);
						$("#address-content select option[value="+details.IDMMCountry.toLowerCase()+"]").attr("selected","selected");
	        		$('#card-register input[type=submit]:first').click(function () {
	        			$('#card-register input[type=submit]:first').parent().html('<p id="info-box"><img src="./?a=4290"/> '+_("Please wait...")+'</p>');	                
	        			var details = {
							CardIssueNumber: 		($('#card-register input[name=CardIssueNumber]').val () || ''),
							CardNumber:	 			($('#card-register input[name=CardNumber]').val () || ''),
							EndOfValidityMonth: 	($('#card-register select[name=EndOfValidityMonth]').val () || ''),
							EndOfValidityYear: 		($('#card-register select[name=EndOfValidityYear]').val () || ''),
							NameAsOnCard: 			($('#card-register input[name=NameAsOnCard]').val () || ''),
							StartOfValidityMonth: 	($('#card-register select[name=StartOfValidityMonth]').val () || ''),
							StartOfValidityYear: 	($('#card-register select[name=StartOfValidityYear]').val () || '')
	        			};
	        			var response = uWinAccount.api.RegisterCard (details);
	        			if (typeof (response) == 'number' || typeof (response) == 'string') {
							$('#info-box').html(''+_("Card registration successful."));
			           	} else if (typeof (response) == 'object') {
							if (typeof (response.WCFApplicationException) != 'undefined') {
								$('#info-box').html(response.WCFApplicationException.Message);	                
							}	
						}	
	        		});
	        	}	

	        }
	        //Deposit page for neteller only
	        else if ($('#deposit-page-neteller').html() != null) {
	        	if (vget("instruction")!="" && vget("type")!="") {
	        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
	        		if (typeof(payment) != 'undefined' && payment!=false) {
	        			$('#min-deposit').html(''+_("Minimum deposit")+': '+payment.MinDepositAmount+_("%currency%"));
	        			$('div.form-row-submit button:first').click (function () {
							var proceed = true;

							$('#deposit-page-neteller .req').each(function (i) {
								if ($(this).val() == '') {
									$(this).css('background-color','#ff8888');
									proceed = false;
								} else {
									$(this).css('background-color','white');
								}
							});
							
							if (proceed) {
								uWinAccount.ui.MakeDeposit();
							} else {
								alert(_('Please fill the required fields'));
							}
						});
	        		} else {
	            		$('#deposit-page-neteller').hide();
	        		}	
	        	} else if (vget("completed")==1 && vget("cancel")==1) {
	        		// transaction canceled
            		$('#deposit-page-next').hide();
            		$('#transaction-status').show();
					$('#status-box').html(_("The deposit transaction was cancelled."));
	        	} else if (vget("completed")==1) {
	        		// transaction complete
            		$('#deposit-page-next').hide();
            		$('#transaction-status').show();
					$('#status-box').html(_("The deposit transaction was successful!"));
	        	} else {
	        		$('#deposit-page-next').hide();
	        	}	
	        }	
	        //Deposit page next version for moneybookers only
	        else if ($('#deposit-page-next').html() != null) {
	        	if (vget("instruction")!="" && vget("type")!="") {
	        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
	        		if (typeof(payment) != 'undefined' && payment!=false) {
	        			$('#min-deposit').html(''+_("Minimum deposit")+': '+payment.MinDepositAmount+_("%currency%"));
	        			$('div.form-row-submit button:first').click (function () {
							var proceed = true;

							$('#deposit-page-next .req').each(function (i) {
								if ($(this).val() == '') {
									$(this).css('background-color','#ff8888');
									proceed = false;
								} else {
									$(this).css('background-color','white');
								}
							});
							
							if (proceed) {
								uWinAccount.ui.MakeDeposit();
							} else {
								alert(_('Please fill the required fields'));
							}
						});
	        		} else {
	            		$('#deposit-page-next').hide();
	        		}	
	        	} else if (vget("completed")==1 && vget("cancel")==1) {
	        		// transaction canceled
            		$('#deposit-page-next').hide();
            		$('#transaction-status').show();
					$('#status-box').html(_("The deposit transaction was cancelled."));
	        	} else if (vget("completed")==1) {
	        		// transaction complete
            		$('#deposit-page-next').hide();
            		$('#transaction-status').show();
					$('#status-box').html(_("The deposit transaction was successful!"));
					var amount = uWinAccount.api.GetMoneybookersDeposit('moneybookersDeposit');
					if (amount!=false) {
						var url = window.location.protocol+'//'+window.location.hostname+window.location.pathname;
						var lang = 'en';

						if (document.cookie.length>0) {
							c_start=document.cookie.indexOf ("lang=");
							if (c_start!=-1) {
								c_start=c_start + 5;
								c_end=document.cookie.indexOf (";",c_start);
								if (c_end==-1) c_end=document.cookie.length;
								lang = unescape(document.cookie.substring(c_start,c_end));
						    }
						}
						lang = lang.toLowerCase();
						$('#status-box').append('<img src="https://reporting.youwin.com/cgi-bin/rr.cgi/images/blank.gif?nourl=' + url + '/deposit-confirm&language='+lang+'&deposit_confirm=confirm&deposit_val='+amount+'&deposit_type=moneybookers" width="1" height="1"/>');
				        var details = uWinAccount.api.GetPersonalDetails();
						if (typeof(details)!='undefined' && typeof(details.UserName)!='undefined') {
							$('#status-box').append('<iframe src="https://ee.connextra.com/universalTag?client=YouWin&id=177829&page=depositconfirm&ac='+details.UserName+'&val='+amount+'" width="0" height="0" scrolling="no" frameborder="0" style="border-width:0"></iframe>');
						}
						uWinAccount.api.UpdateBalanceOnTop();						
					}
	        	} else {
	        		$('#deposit-page-next').hide();
	        	}	
	        }
	        //Deposit page next version for credit cards only
	        else if ($('#deposit-page-next-cc').html() != null) {
	        	if (vget("instruction")!="" && vget("type")!="") {
	        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
	        		if (typeof(payment) != 'undefined' && payment!=false) {
	        			$('#min-deposit').html(''+_("Minimum deposit")+': '+payment.MinDepositAmount+_("%currency%"));
	        			$('div.form-row-submit button:first').click (function () {
							var proceed = true;

							$('#deposit-page-next-cc .req').each(function (i) {
								if ($(this).val() == '') {
									$(this).css('background-color','#ff8888');
									proceed = false;
								} else {
									$(this).css('background-color','white');
								}
							});
							
							if (proceed) {
								uWinAccount.ui.MakeDeposit();
							} else {
								alert(_('Please fill the required fields'));
							}
						});
	        		} else {
	            		$('#deposit-page-next-cc').hide();
	        		}	
	        	} else if (vget("completed")==1 && vget("cancel")==1) {
	        		// transaction canceled
            		$('#deposit-page-next-cc').hide();
            		$('#transaction-status').show();
					$('#status-box').html(_("The deposit transaction was cancelled."));
	        	} else if (vget("completed")==1) {
	        		// transaction complete
            		$('#deposit-page-next-cc').hide();
            		$('#transaction-status').show();
					$('#status-box').html(_("The deposit transaction was successful!"));
	        	} else {
	        		$('#deposit-page-next-cc').hide();
	        	}	
	        }	
        //Deposit page
        else if ($('#deposit-page').html() != null) {
        	if (vget("instruction")!="" && vget("type")!="") {
        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
        		if (typeof(payment) != 'undefined' && payment!=false) {
        			$('#deposit-page div.first p.short:first').html(''+_("Payment Type")+': '+payment.MMSITypeName);
        			$('#min-deposit').html(''+_("Minimum deposit")+': '+payment.MinDepositAmount+_("%currency%"));
        			$('#submit-button-deposit').click(uWinAccount.ui.MakeDeposit);
        			switch (payment.IDMMSIType) {
        				case 'MC':
        				case 'VC':
        				case 'DE':
        					$('#card-number p').html('<b>'+_("Card number")+':</b> '+payment.DisplayLabel);	
        					break;
        				case 'Moneybookers':
        					$('#card-number').hide();
        					$('#cv2').hide();
        					$('#moneybookers-email').show();
        					break;
        			}
        			
        		} else {
            		$('#deposit-page').hide();
        		}	
        	} else if (vget("completed")==1 && vget("cancel")==1) {
        		// transaction canceled
        		$('#deposit-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The deposit transaction was cancelled.")+'<br/><br/></div>');
        	} else if (vget("completed")==1) {
        		// transaction complete
        		$('#deposit-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The deposit transaction was successful!")+'</br/><br/></div>');
        	} else {
        		$('#deposit-page').hide();
        	}	
        }	
        //Withdraw page for credit cards
        else if ($('#withdraw-page-cc').html() != null) {
        	if (vget("instruction")!="" && vget("type")!="") {
        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
        		if (typeof(payment) != 'undefined' && payment!=false) {
		            var balances = uWinAccount.api.GetBalances();
					$("#sport-balance").val(balances['tradingBalance']);
        			$('#min-withdraw').html(''+_("Minimum withdraw")+': '+payment.MinDepositAmount+_("%currency%"));
        			
					$('div.form-row-submit button:first').click(function () {
						var proceed = true;

						$('#withdraw-page-cc .req').each(function (i) {
							if ($(this).val() == '') {
								$(this).css('background-color','#ff8888');
								proceed = false;
							} else {
								$(this).css('background-color','white');
							}
						});
						
						if (proceed) {
							if (parseFloat($('#withdraw-amount').val())>parseFloat($('#sport-balance').val())) {
								$('#withdraw-amount').css('background-color','#ff8888');
								alert(_('The requested amount is higher than your balance.'));
							} else {
								uWinAccount.ui.MakeWithdraw();
							}
						} else {
							alert(_('Please fill the required fields'));
						}	
					});
        		} else {
            		$('#withdraw-page').hide();
        		}	
        	} else if (vget("completed")==1 && vget("cancel")==1) {
        		// transaction canceled
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was cancelled")+'<br/><br/></div>');
        	} else if (vget("completed")==1) {
        		// transaction complete
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was successful!")+'</br/><br/></div>');
        	} else {
        		$('#withdraw-page').hide();
        	}	
        }
        //Withdraw page for neteller
        else if ($('#withdraw-page-nt').html() != null) {
        	if (vget("instruction")!="" && vget("type")!="") {
        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
        		if (typeof(payment) != 'undefined' && payment!=false) {
		            var balances = uWinAccount.api.GetBalances();
					$("#sport-balance").val(balances['tradingBalance']);	
        			$('#min-withdraw').html(''+_("Minimum withdraw")+': '+payment.MinDepositAmount+_("%currency%"));
        			
					$('div.form-row-submit button:first').click(function () {
						var proceed = true;

						$('#withdraw-page-nt .req').each(function (i) {
							if ($(this).val() == '') {
								$(this).css('background-color','#ff8888');
								proceed = false;
							} else {
								$(this).css('background-color','white');
							}
						});
						
						if (proceed) {
							if (parseFloat($('#withdraw-amount').val())>parseFloat($('#sport-balance').val())) {
								$('#withdraw-amount').css('background-color','#ff8888');
								alert(_('The requested amount is higher than your balance.'));
							} else {
								uWinAccount.ui.MakeWithdraw();
							}
						} else {
							alert(_('Please fill the required fields'));
						}	
					});
        		} else {
            		$('#withdraw-page').hide();
        		}	
        	} else if (vget("completed")==1 && vget("cancel")==1) {
        		// transaction canceled
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was cancelled")+'<br/><br/></div>');
        	} else if (vget("completed")==1) {
        		// transaction complete
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was successful!")+'</br/><br/></div>');
        	} else {
        		$('#withdraw-page').hide();
        	}	
        }
        //Withdraw page for moneybookers
        else if ($('#withdraw-page-mb').html() != null) {
        	if (vget("instruction")!="" && vget("type")!="") {
        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
        		if (typeof(payment) != 'undefined' && payment!=false) {
		            var balances = uWinAccount.api.GetBalances();
					$("#sport-balance").val(balances['tradingBalance']);	
        			$('#min-withdraw').html(''+_("Minimum withdraw")+': '+payment.MinDepositAmount+_("%currency%"));
        			
					$('div.form-row-submit button:first').click(function () {
						var proceed = true;

						$('#withdraw-page-mb .req').each(function (i) {
							if ($(this).val() == '') {
								$(this).css('background-color','#ff8888');
								proceed = false;
							} else {
								$(this).css('background-color','white');
							}
						});
						
						if (proceed) {
							if (parseFloat($('#withdraw-amount').val())>parseFloat($('#sport-balance').val())) {
								$('#withdraw-amount').css('background-color','#ff8888');
								alert(_('The requested amount is higher than your balance.'));
							} else {
								uWinAccount.ui.MakeWithdraw();
							}
						} else {
							alert(_('Please fill the required fields'));
						}	
					});
        		} else {
            		$('#withdraw-page').hide();
        		}	
        	} else if (vget("completed")==1 && vget("cancel")==1) {
        		// transaction canceled
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was cancelled")+'<br/><br/></div>');
        	} else if (vget("completed")==1) {
        		// transaction complete
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was successful!")+'</br/><br/></div>');
        	} else {
        		$('#withdraw-page').hide();
        	}	
        }
        //Withdraw page
        else if ($('#withdraw-page').html() != null) {
        	if (vget("instruction")!="" && vget("type")!="") {
        		var payment = uWinAccount.api.GetPaymentInstrument(vget("instruction"));
        		if (typeof(payment) != 'undefined' && payment!=false) {
        			$('#withdraw-page div.first p.short:first').html(''+_("Payment Type")+': '+payment.MMSITypeName);
        			$('#min-deposit').html(''+_("Minimum withdraw")+': '+payment.MinDepositAmount+_("%currency%"));
        			$('#submit-button-withdraw').click(uWinAccount.ui.MakeWithdraw);
        			switch (payment.IDMMSIType) {
        				case 'MC':
        				case 'VC':
        					$('#card-number p').html('<b>'+_("Card number")+':</b> '+payment.DisplayLabel);	
        					$('#cv2').hide();
        					break;
        				case 'Moneybookers':
        					$('#card-number').hide();
        					$('#cv2').hide();
        					break;
        			}
        			
        		} else {
            		$('#withdraw-page').hide();
        		}	
        	} else if (vget("completed")==1 && vget("cancel")==1) {
        		// transaction canceled
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was cancelled")+'<br/><br/></div>');
        	} else if (vget("completed")==1) {
        		// transaction complete
        		$('#withdraw-page div.first p.short:first').html(_("Deposit"));
				$('#card-number').hide();
				$('#cv2').hide();
				$('#amount-box').hide();
				$('#password-box').hide();
				$('#status-box').html('<div style="text-align: center"><br/>'+_("The withdraw transaction was successful!")+'</br/><br/></div>');
        	} else {
        		$('#withdraw-page').hide();
        	}	
        }

		//Poker nickname selection
		else if ($('div.poker-nickname').html() != null) {
			$('div.poker-nickname .submit-button').each(function(){
				$(this).click(function () {
					if ($('#poker_nickname').val()!='') {
						if ($('#poker_nickname').val().match(/^[a-zA-Z0-9@$*_\-+]{3,11}$/)) {
							var response = uWinAccount.api.CreatePokerAccount($('#poker_nickname').val());
							if (response) {
								$('div.poker-nickname .submit-button').hide();
								if (confirm(_('Your poker account was created successfully.\nPress OK to go to the Youwin Homepage.'))) {
									window.location='http://www.youwin.com';
								} 
							} else {
								alert (_('There was a problem creating you poker account - nickname taken or technical error.\nPlease check that you don\'t have "," (comma) char in your account password.\nIf that\'s the case - please change the password first, then try to create the poker nickname again.'));
							}
						} else {
							alert (_('Nickname contains invalid characters.'));
						}
					}
				});
			}); 
		}	
		
        //Withdraw payment instruments list
        else if ($('#withdraw-payment-instruments').html() != null) {
        	var dMethods = uWinAccount.api.GetActivePaymentInstruments('P');
        	if (vget("instruction")=="") {
        		if (dMethods!=null && typeof(dMethods) != 'undefined' && typeof (dMethods.PaymentInstrument) != 'undefined') {
        			if (typeof (dMethods.PaymentInstrument[0]) != 'undefined') {
						$('#payment-instruments-container').empty();
        				dMethods.PaymentInstrument.each(function (i) {
        					$('#payment-details-template .payment-label').html(i.MMSITypeName+((i.DisplayLabel) ? (' / '+i.DisplayLabel) : ''));
        					$('#payment-details-template .payment-used').html(''+_("Last used on")+': '+((i.TSLastUsed) ? (i.TSLastUsed.replace(/T/,' ')) : 'n/a'));
        					$('#payment-details-template .min-withdrawal').html(''+_("Minimum withdrawal")+': '+i.MinWithdrawalAmount);
        					$('#payment-details-template .submit-button').attr('id',i.IDMMSIInstruction+'#'+i.IDMMSIType);
        					$('#payment-details-template div:first').attr('class', i.IDMMSIType+' '+i.IDMMSIClass);
        					$('#payment-instruments-container').append($('#payment-details-template').html());
        				});
        				$('#payment-instruments-container .submit-button').each(function(){
        					$(this).click(function () {
								switch (this.id.split('#')[1]) {
				    				case 'VE':
				    				case 'VC':
				    				case 'DE':
	   									window.location=window.location.href.replace(/withdraw-payment-instruments/,'credit-card-withdraw')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1]+'&_nocache';
										break;
									case 'Moneybookers':
	   									window.location=window.location.href.replace(/withdraw-payment-instruments/,'moneybookers-withdraw')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1]+'&_nocache';
										break;
									case 'NT':
	   									window.location=window.location.href.replace(/withdraw-payment-instruments/,'neteller-withdraw')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1]+'&_nocache';
										break;
								}
        					});
        				}); 
        			} else {
						$('#payment-instruments-container').empty();
        				var i = dMethods.PaymentInstrument;
        				$('#payment-details-template .payment-label').html(i.MMSITypeName+((i.DisplayLabel) ? (' / '+i.DisplayLabel) : ''));
        				$('#payment-details-template .payment-used').html(''+_("Last used on")+': '+((i.TSLastUsed) ? (i.TSLastUsed.replace(/T/,' ')) : 'n/a'));
        				$('#payment-details-template .min-withdrawal').html(''+_("Minimum withdrawal")+': '+i.MinWithdrawalAmount);
        				$('#payment-details-template .submit-button').attr('id',i.IDMMSIInstruction+'#'+i.IDMMSIType);
        				$('#payment-details-template div:first').attr('class', i.IDMMSIType+' '+i.IDMMSIClass);
        				$('#payment-instruments-container').append($('#payment-details-template').html());
        				$('#payment-instruments-container .submit-button').each(function(){
        					$(this).click(function () {
								switch (this.id.split('#')[1]) {
				    				case 'VE':
				    				case 'VC':
				    				case 'DE':
	   									window.location=window.location.href.replace(/withdraw-payment-instruments/,'credit-card-withdraw')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1]+'&_nocache';
										break;
									case 'Moneybookers':
	   									window.location=window.location.href.replace(/withdraw-payment-instruments/,'moneybookers-withdraw')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1]+'&_nocache';
										break;
									case 'NT':
	   									window.location=window.location.href.replace(/withdraw-payment-instruments/,'neteller-withdraw')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1]+'&_nocache';
										break;
								}
							});
        				}); 
        			}
        		}
        	} else {
        		alert('display deposit');
        	}	
        }        
        //Deposit payment instruments list
        else if ($('#deposit-payment-instruments').html() != null) {
        	var dMethods = uWinAccount.api.GetActivePaymentInstruments('R');
        	if (vget("instruction")=="") {
        		if (dMethods!=null && typeof(dMethods) != 'undefined' && typeof (dMethods.PaymentInstrument) != 'undefined' && typeof(dMethods)!='') {
        			if (typeof (dMethods.PaymentInstrument[0]) != 'undefined') {
						$('#payment-instruments-container').empty();
        				dMethods.PaymentInstrument.each(function (i) {
        					$('#payment-details-template .payment-label').html(i.MMSITypeName+((i.DisplayLabel) ? (' / '+i.DisplayLabel) : ''));
        					$('#payment-details-template .payment-used').html(''+_("Last used on")+': '+((i.TSLastUsed) ? (i.TSLastUsed.replace(/T/,' ')) : 'n/a'));
        					$('#payment-details-template .min-deposit').html(''+_("Minimum deposit")+': '+i.MinDepositAmount+_("%currency%"));
        					$('#payment-details-template .submit-button').attr('id',i.IDMMSIInstruction+'#'+i.IDMMSIType);
        					$('#payment-details-template div:first').attr('class', i.IDMMSIType+' '+i.IDMMSIClass);
        					$('#payment-instruments-container').append($('#payment-details-template').html());
        				});
        				$('#payment-instruments-container .submit-button').each(function(){
        					$(this).click(function () {
								switch (this.id.split('#')[1]) {
				    				case 'VE':
				    				case 'VC':
				    				case 'DE':
				    				case 'MC':
				    				case 'MA':
				    				case 'SL':
				    				case 'SLO':
	        							window.location=window.location.href.replace(/deposit-payment-instruments/,'deposit-with-credit-card')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1];
										break;
									case 'Moneybookers':
	        							window.location=window.location.href.replace(/deposit-payment-instruments/,'moneybookers-deposit')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1];
										break;
									case 'NT':
	        							window.location=window.location.href.replace(/deposit-payment-instruments/,'neteller-deposit')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1];
										break;
								}
        					});
        				});
        			} else {
        				var i = dMethods.PaymentInstrument;
						$('#payment-instruments-container').empty();
        				$('#payment-details-template .payment-label').html(i.MMSITypeName+((i.DisplayLabel) ? (' / '+i.DisplayLabel) : ''));
        				$('#payment-details-template .payment-used').html(''+_("Last used on")+': '+((i.TSLastUsed) ? (i.TSLastUsed.replace(/T/,' ')) : 'n/a'));
        				$('#payment-details-template .min-deposit').html(''+_("Minimum deposit")+': '+i.MinDepositAmount+_("%currency%"));
        				$('#payment-details-template .submit-button').attr('id',i.IDMMSIInstruction+'#'+i.IDMMSIType);
        				$('#payment-details-template div:first').attr('class', i.IDMMSIType+' '+i.IDMMSIClass);
        				$('#payment-instruments-container').append($('#payment-details-template').html());
        				$('#payment-instruments-container .submit-button').each(function(){
        					$(this).click(function () {
								switch (this.id.split('#')[1]) {
				    				case 'VE':
				    				case 'VC':
				    				case 'DE':
				    				case 'MC':
				    				case 'MA':
				    				case 'SL':
				    				case 'SLO':
	        							window.location=window.location.href.replace(/deposit-payment-instruments/,'deposit-with-credit-card')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1];
										break;
									case 'Moneybookers':
	        							window.location=window.location.href.replace(/deposit-payment-instruments/,'moneybookers-deposit')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1];
										break;
									case 'NT':
	        							window.location=window.location.href.replace(/deposit-payment-instruments/,'neteller-deposit')+'?instruction='+this.id.split('#')[0]+'&type='+this.id.split('#')[1];
										break;
								}
							});
        				});
        		
        			}	 
        		} else {
					$('#payment-instruments-container').empty();
				}
        	} else {
        		alert('display deposit');
        	}	
        }
        //Transfer funds
        else if ($("#fromFunds").html() != null) {
            var balances = uWinAccount.api.GetBalances();
            $("p.cash span.poker").html(balances['poker']);
            $("p.cash span.casino").html(balances['casino']);
            //$("p.cash span.sport").html(balances['main']);
$("p.cash span.sport").html(balances['tradingBalance']);
            account = balances['account'];
            
            $("#fromFunds").change(function () {
                if ($(this).val() == 22) {
                    $('#toFunds option[value=22]').hide();
$('#toFunds option[value=7],#toFunds option[value=8]').show();
                    $('#toFunds option[value=7]').attr('selected','selected');
                } 
			
else {
                    $('#toFunds option[value=22]').show();
  $('#toFunds option[value=7],#toFunds option[value=8]').hide();
                    $('#toFunds option[value=22]').attr('selected','selected');
                }
            });

            $("#toFunds").change(function () {
                if ($(this).val() == 22) {
                    //$('#fromFunds option[value=22]').hide();
                    $('#fromFunds option[value=7]').attr('selected','selected');
                } else {
                    //$('#fromFunds option[value=22]').show();
                    $('#fromFunds option[value=22]').attr('selected','selected');
                }
            });

            $('#transferAmount').bind("change keyup", function () {
                // parse out anything that is not number or dot
                $(this).val($(this).val().replace(/[^0-9|\.|,]/,""));

                // parse out unneccessary dots and decimals
                if (!$(this).val().match(/^[0-9]+([\.|,][0-9]{0,2})?$/)) {
                    var stake = $(this).val().replace(/,/,'.').split(".");
                    if (stake[0] == "") {
                        if (stake[1] == undefined) {
                            stake[0] = "";
                        } else {
                            stake[0] = "0";
                        }
                    }
                    if (stake[1] == undefined || stake[1] == "") {
                        $(this).val(stake[0]);
                    } else {
						if ($(this).val().indexOf('.') != -1) {
                        	$(this).val(stake[0] + "." + stake[1].substr(0, 2));
						} else {
                        	$(this).val(stake[0] + "," + stake[1].substr(0, 2));
						}	
                    }
                }            	
            });
            
            $("#transferButton").click(function () {
            	if ((parseFloat($('#transferAmount').val().replace(/,/,'.')) || 0) == 0) {
                    alert(_("Please enter amount to transfer"));
            	} else {
            		var games = new Array ();
            		games[7] 	= 'casino';
            		games[8] 	= 'poker';
            		games[22]	= 'sport';
 
            		if (parseFloat($('#transferAmount').val().replace(/,/,'.')) > parseFloat($('p.cash span.'+games[$('#fromFunds option:selected').val()]).html())) {
            			alert(_("Amount to transfer is higher than your balance."));		
            		} else {
                		var balances = uWinAccount.api.GetBalances();
						if (balances['casinoBonus']>0 && $('#fromFunds option:selected').val()==7) {
							alert(_("You still have EUR %s in bonus funds and cannot transfer your chips to your main account until you have met the wagering requirements. Please contact support if you have any questions.").replace(/%s/,balances['casinoBonus']));
						} else if (($('#fromFunds option:selected').val()==8 || $('#toFunds option:selected').val()==8) && !balances['pokerAccount']) {
							var msg = _("It seems that you don't have a Poker account set up already. Press OK to create a poker account, or press Cancel to continue."); 
							if (confirm(msg)) {
								var lang = 'en';

								if (document.cookie.length>0) {
									c_start=document.cookie.indexOf ("lang=");
									if (c_start!=-1) {
										c_start=c_start + 5;
										c_end=document.cookie.indexOf (";",c_start);
										if (c_end==-1) c_end=document.cookie.length;
										lang = unescape(document.cookie.substring(c_start,c_end));
								    }
								}

								lang = lang.toLowerCase();
								window.location='https://myaccount.youwin.com/'+lang+'/poker/poker-nickname';
							} 
						} else {	
            				var transfer = uWinAccount.api.PngTransferFunds(account, parseFloat($('#transferAmount').val().replace(/,/,'.')), $('#fromFunds option:selected').val(), $('#toFunds option:selected').val());
                        	if (typeof(transfer)=="object" && transfer.error!=null) {
                        		alert(_("There was an error while transfering funds")+":\n"+transfer.error.message);
                        	} else {
	                    		balances = uWinAccount.api.GetBalances();
                        		$("p.cash span.poker").html(balances['poker']);
                        		$("p.cash span.casino").html(balances['casino']);
                        		$("p.cash span.sport").html(balances['main']);
								$("#transferAmount").val("");
								alert(_('Your transfer has been successfully completed.'));
if ($('#casino_transfer_balance').length) {
	$('#login-box p.hide_b span.left').html(balances['casino']);
	$('#bal_one').html(balances['casino']);
}

                        	}
						}			
            		}	
            	}	
            });
        }
        //End Edit Details
        else if ($(".change_passwords_inputs").html() != null) {
            uWinAccount.api.checkLoggedIn("#content");
            required_1 = {
                'old_password': 1,
                'new_password_1': 1,
                'new_password_2': 1

            };
            messages_1 = {

                'new_password_1': _("Contains invalid characters"),
                'new_password_2': _("Contains invalid characters"),
                'old_password': _("Bad Password")

            };

            // disable next step button
            document.getElementById("submit").disabled = true;
            // get all form inputs except hiddens
            var inputs = $("input[type!='hidden'],select");
            uWinAccount.ChangePasswordValidate.construct(required_1, messages_1, inputs);
            $("#submit").click(function (event) {
                event.preventDefault();
                uWinAccount.api.ChangePassword($("#new_password_1"), $("#old_password"));

            });

            // apply events to inputs and selects
            $(".change_passwords_inputs input:not(#submit)").each(function () {
                $(this).bind("blur", function () {
                    uWinAccount.ChangePasswordValidate.form($(this));
                });
            });
        }
        //Secret question fetch
		else if ($('#q1790_q5').html()!=null) {
			var q = uWinAccount.api.GetSecretQuestions();
			if (typeof(q)!='undefined') {
				for (var i in q) { $('#q1790_q5').append('<option value="'+i+'">'+q[i]+'</option>'); };	
			}
		}
        //End password
else if($(".forgotten_step_one").html()!=null){
	$("#popupclose").click(function(e){
		e.preventDefault();
		parent.$("#cboxClose").click();
	});
	$("#q5201_q6 option:gt(0)").remove();
	var dat = new Date;
	for(i=dat.getFullYear()-18;i>dat.getFullYear()-110;i--)
		$("#q5201_q6").append("<option value="+i+">"+i+"</option>");
		
		
		$("#form_email_5199").submit(function() {



if(uWinAccount.api.SecretFail==0){
	var dateFor = "T00:00:00";
	var fd = $("#q5201_q5").val();
	var fm = $("#q5201_q3").val();
	fd  = parseInt(parseInt(fd)+1);
	fm = parseInt(parseInt(fm)+1);
	if(fd <10){
	fd = "0"+fd;
	}
	if(fm <10){
	fm="0"+fm;
	}
	dateFor = $("#q5201_q6").val()+"-"+fm+"-"+fd+dateFor;
  	uWinAccount.api.GetSecretQuestionTest($("#q5201_q1").val(),dateFor);
return false;
}
           
        });
		
	    required_1 = {
	        'q5201_q1': 1,
	        'q5201_q5': 1,
	        'q5201_q3': 1,
	        'q5201_q6': 1
	    };

	    messages_1 = {
	        'q5201_q1': _("Contains invalid characters"),
	        'q5201_q5': _("Day is required"),
	        'q5201_q3': _("Month is required"),
	        'q5201_q6': _("Year is required")
	        
	    };


	    // get all form inputs except hiddens
	    var inputs = $("input[type!='hidden'],select,textarea[class!='hidden']");


	    	document.getElementById("form_email_5199_submit").disabled = true;
	        uWinAccount.forgottenValidate.construct(required_1, messages_1, inputs);

	        // draw correct option values for date selects
	  

	    // apply events to inputs and selects
	    $("#form_email_5199 input[type!='checkbox'],#form_email_5199 textarea").each(function() {
	        //console.log($(this).attr("id"));
	        $(this).bind("focus keyup",
	        function() {
	            uWinAccount.forgottenValidate.form($(this));
	        });
	    });
	    $("#form_email_5199 select").each(function() {
	        $(this).bind("focus change blur",
	        function() {
	            uWinAccount.forgottenValidate.form($(this));
	        });
	    });

		
		
	
}
else if($(".forgotten_question").html()!=null){
	$("#popupclose").click(function(e){
		e.preventDefault();
		parent.$("#cboxClose").click();
	});
	var dateFor = "T00:00:00";
	$("#forgotten_day").val(parseInt(parseInt($("#forgotten_day").val())+1));
	$("#forgotten_month").val(parseInt(parseInt($("#forgotten_month").val())+1));
	if($("#forgotten_day").val().length <2){
		$("#forgotten_day").val("0"+$("#forgotten_day").val());
	}
	if($("#forgotten_month").val().length <2){
		$("#forgotten_month").val("0"+$("#forgotten_month").val());
	}
	dateFor = $("#forgotten_year").val()+"-"+$("#forgotten_month").val()+"-"+$("#forgotten_day").val()+dateFor;
	uWinAccount.api.GetSecretQuestion($("#q5201_q1").val(),dateFor);

	
	
	
	
    required_1 = {
        'q5202_q1': 1,
         'q5202_q4_2': 1,
        'q5202_q4': 1
    };

    messages_1 = {
        'q5202_q1': _("Answer is required"),
        'q5202_q4_2': _("Contains invalid characters"),
        'q5202_q4': _("Contains invalid characters")
    };


    // get all form inputs except hiddens
    var inputs = $("input[type!='hidden'],select,textarea[class!='hidden']");


    	document.getElementById("form_email_5199_submit").disabled = true;
        uWinAccount.forgottenValidate.construct(required_1, messages_1, inputs);


        //$("#form_email_1784_submit").submit(function(event) {
      // 	uWinAccount.api.SetPasswordUsingSQuestion($("#q5201_q1").val(),$("#q5202_q1").val(),$("#q5202_q4").val());
    

    // apply events to inputs and selects
    $("#form_email_5199 input[type!='checkbox'],#form_email_5199 textarea").each(function() {
        //console.log($(this).attr("id"));
        $(this).bind("focus keyup",
        function() {
            uWinAccount.forgottenValidate.form($(this));
        });
    });
    $("#form_email_5199 select").each(function() {
        $(this).bind("focus change blur",
        function() {
            uWinAccount.forgottenValidate.form($(this));
        });
    });

	
	
	
}else if($(".setpasswrduque").html()!=null){
	$("#popupclose").click(function(e){
		e.preventDefault();
		parent.$("#cboxClose").click();
	});
	uWinAccount.api.SetPasswordUsingSQuestion($("#q5201_q1").val(),$("#q5202_q1").val(),$("#q5202_q4").val(),$("#q5202_q6").val());
}
        else if ($(".transaction-view-option").html() != null) {
	uWinAccount.api.isHistoryToBeGenerated();
            var months_amount = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

            var dat = new Date();

            for (i = dat.getFullYear(); i >= 2000; i--) $(".year_select").append("<option value=" + i + ">" + i + "</option>");


            $(".year_select").change(function () {
                var $that = $(this).parent("div");
                var year_check = parseInt($(this).val());
                if (year_check % 400 && (year_check % 4 || !(year_check % 100)) && $(this).prev(".month_select").val() == 2) $that.find(".day_select option[value=29]").remove();
                else {
                    if ($that.find(".day_select option[value=29]").val() != '29') $that.find(".day_select").append("<option value='29'>29</option>");

                }

            });
            $(".month_select").change(function () {
                var $that = $(this).parent("div");
                if ($(this).val() == 2) {

                    var year_check = parseInt($that.find(".year_select").val());

                    if (year_check % 400 && (year_check % 4 || !(year_check % 100))) $that.find(".day_select option[value=29]").remove();
                    $that.find(".day_select option[value=30]").remove();
                    $that.find(".day_select option[value=31]").remove();
                } else {
                    $that.find(".day_select option[value=30]").remove();
                    $that.find(".day_select option[value=31]").remove();
                    if ($that.find(".day_select option[value=29]").val() != '29') $that.find(".day_select").append("<option value='29'>29</option>");
                    $that.find(".day_select").append("<option value='30'>30</option>");
                    if (months_amount[($(this).val() - 1)] == 31) $that.find(".day_select").append("<option value='31'>31</option>");

                }


            });
            $(".month_select option[value=" + (dat.getMonth() + 1) + "]").attr("selected", "selected");

            $(".day_select option[value=" + dat.getDate() + "]").attr("selected", "selected");

            $(".generate_view_user_history").click(function () {
                var from_month = parseInt($(".from_date .month_select").val());
                if (from_month < 10) from_month = "0" + from_month;
                var from_day = parseInt($(".from_date .day_select").val());
                if (from_day < 10) from_day = "0" + from_day;

                var to_month = parseInt($(".to_date .month_select").val());
                if (to_month < 10) to_month = "0" + to_month;
                var to_day = parseInt($(".to_date .day_select").val());
/*
                to_day = to_day - 1; //finsoft return to_day + 1 so i make it to -1
if(to_day==0)
if($(".to_date .month_select").val()-2<0) 
to_day=31;
else
 to_day = months_amount[$(".to_date .month_select").val()-2];
*/
                if (to_day < 10) to_day = "0" + to_day;

                var from = $(".from_date .year_select").val() + "-" + from_month + "-" + from_day + "T" + "00" + ":" + "00" + ":" + "00";
                var to = $(".to_date .year_select").val() + "-" + to_month + "-" + to_day + "T" + 23 + ":" + 59 + ":" + 59;
                uWinAccount.api.ViewUserHistoryGenerate(from, to, $(" input[name=history_type]:checked").val());
            });
            uWinAccount.api.ReturnCurrentBalance($(".balance span"), _("%currency%"));
            uWinAccount.api.checkLoggedIn("#content");

        } //end history
        else if ($(".set_deposit_limit").html() != null) {
            uWinAccount.api.setDepositLimitFillIn();
            uWinAccount.api.checkLoggedIn("#content");
            required_1 = {
                'password': 1,
                'DepositLimit': 1

            };

            messages_1 = {
                'DepositLimit': _("Contains invalid characters"),
                'password': _("Bad Password")
            };

            // disable next step button
            document.getElementById("submit").disabled = true;

            // get all form inputs except hiddens
            var inputs = $("input[type!='hidden'],select");

            // apply diffrent validation rules to fields
            uWinAccount.SetDepositLimitValidate.construct(required_1, messages_1, inputs);
            $("#submit").click(function (event) {
                event.preventDefault();
                uWinAccount.api.setDepositLimit();

            });

            // apply events to inputs and selects
            $(".set_deposit_limit input:not(#submit)").each(function () {
                $(this).bind("focus keyup", function () {
                    uWinAccount.SetDepositLimitValidate.form($(this));
                });
            });

        } //end set deposit
		else if($("#bet_id").html()!=null){
			
			   uWinAccount.api.checkLoggedIn(".account-box");
	            uWinAccount.api.generateBetDetails();
		}
		else if($("#history-details").html()!=null){
			uWinAccount.api.checkLoggedIn("#history-details");
		    uWinAccount.api.generateAccountLanding();
		
		
		
		
			var months_amount = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

			var dat = new Date();

			for (i = dat.getFullYear(); i >= 2000; i--) $(".to_year,.from_year").append("<option value=" + i + ">" + i + "</option>");


			$(".to_year").change(function () {
			    var year_check = parseInt($(this).val());
			    if (year_check % 400 && (year_check % 4 || !(year_check % 100)) && $(".to_month").val() == 2) $(".to_day option[value=29]").remove();
			    else {
			        if ($(".to_day option[value=29]").val() != '29') $(".to_day").append("<option value='29'>29</option>");

			    }

			});
			$(".from_year").change(function () {
			    var year_check = parseInt($(this).val());
			    if (year_check % 400 && (year_check % 4 || !(year_check % 100)) && $(".from_month").val() == 2) $(".from_day option[value=29]").remove();
			    else {
			        if ($(".from_day option[value=29]").val() != '29') $(".from_day").append("<option value='29'>29</option>");

			    }

			});
			$(".to_month").change(function () {
			    if ($(this).val() == 2) {

			        var year_check = parseInt($(".to_month").val());

			        if (year_check % 400 && (year_check % 4 || !(year_check % 100))) $(".to_day option[value=29]").remove();
			        $(".to_day option[value=30]").remove();
			        $(".to_day option[value=31]").remove();
			    } else {
			        $(".to_day option[value=30]").remove();
			        $(".to_day option[value=31]").remove();
			        if ($(".to_day option[value=29]").val() != '29') $(".to_day").append("<option value='29'>29</option>");
			        $(".to_day").append("<option value='30'>30</option>");
			        if (months_amount[($(this).val() - 1)] == 31) $(".to_day").append("<option value='31'>31</option>");

			    }
			});
			$(".from_month").change(function () {
			    if ($(this).val() == 2) {

			        var year_check = parseInt($(".from_month").val());

			        if (year_check % 400 && (year_check % 4 || !(year_check % 100))) $(".from_day option[value=29]").remove();
			        $(".from_day option[value=30]").remove();
			        $(".from_day option[value=31]").remove();
			    } else {
			        $(".from_day option[value=30]").remove();
			        $(".from_day option[value=31]").remove();
			        if ($(".from_day option[value=29]").val() != '29') $(".from_day").append("<option value='29'>29</option>");
			        $(".from_day").append("<option value='30'>30</option>");
			        if (months_amount[($(this).val() - 1)] == 31) $(".from_day").append("<option value='31'>31</option>");

			    }
			});


			$(".to_month option[value=" + (dat.getMonth() + 1) + "]").attr("selected", "selected");
			$(".from_month option[value=" + (dat.getMonth() + 1) + "]").attr("selected", "selected");
			$(".to_day option[value=" + dat.getDate() + "]").attr("selected", "selected");
			$(".from_day option[value=" + dat.getDate() + "]").attr("selected", "selected");

			$("#history-details .go-button").click(function () {
			   	if($("input[name=bets]:checked").val()!=undefined){	
				if($("input[name=bets]:checked").val()=="unsettled") 
				window.open($(".open-bets-link").html(),'newWindow','width=568,scrollbars=1,height=500');
				 else
				uWinAccount.api.accountLandindHistory();
				}
			});
		
		
		
		
		}
        else if ($(".openbets-popup").html() != null) {
            uWinAccount.api.checkLoggedIn(".account-box");
            uWinAccount.api.generateOpenBets();

        } 
		
//END open bets, add transfer etc
        //uWinAccount.api.ReturnCurrentBalance(".balance span",_("%currency%"));
        $(".login-button").click(function () {
            uWinAccount.api.user_login();
        });



        // pageready code here
        // this is a test example!
        //$("#betting-slip-right-box").hide();
        // adds onclick action to every bet selection in content
        $("#content span.selection").each(function (i) {
            $(this).mouseover(function () {
                $(this).removeClass('out');
                $(this).addClass('over');
            });
            $(this).mouseout(function () {
                $(this).removeClass('over');
                $(this).addClass('out');
            });

            if ($(this).find("span.frac").html() != "N/A") {
                $(this).addClass('clickable');
                $(this).click(function (event) {
                    event.preventDefault();
                    var odds = $(this).find("span.frac").html();
                    if (odds == 'EVS') {
                        odds = '1/1';
                    }
                    /* odds = odds.split("/");
              uWinAccount.state.addBet({
                 "IDFOPriceType": "CP",
                 "IDFOSelection": $(this).attr("id").split('/')[1],
                 "PriceDown": parseInt(odds[1]),
                 "PriceUp": parseInt(odds[0])
                 },$(this));
?????
*/
                });
            }
        });



    });
} (jQuery);



//Forgotten details



uWinAccount.forgottenValidate = new

function ($) {
    var self = this;
    this.errorCount = 0;
    this.loginCheck = 0;
    this.nicknameCheck = 0;
    this.currentElement2;
    this.ajaxRun;
    this.currentElement;
    this.currentMsg;
    this.required;
    this.messages;
    this.inputs;
    this.checked_fields = Object();

    this.construct = function (required, messages, inputs) {
        this.required = required;
        this.messages = messages;
        this.inputs = inputs;
        this.inputs.each(function () {
            self.checked_fields[$(this).attr("id")] = 0;
        });
    };
    
    //fix my account section header spacing
    $('div.account-content div.first').css('margin-top','20px');

    // function that validates on reg exp
    this.standard_field = function (element, expression, msg, length) {
        // first check if empty
        if (element.val() == "") {
            // this handles diffrent message for required fields
            if (this.required[element.attr("id")]) {
                // when msg not empty, it means we are on the current field, so need to display default as field is empty
                if (msg != "") msg = _("This field is required");
                this.fieldFail(element, msg);
                return 1;
            } else {
                this.fieldOk(element);
                return 0;
            }
        } else {
            // this checks regular expression
            if (length != null && element.val().length < length) {

                this.fieldFail(element, _("Must be at least 6 characters long"));
                return 1;
            } else if (element.val().match(expression)) {

                if (element.val().match(/^ +$/) && this.required[element.attr("id")]) {
                    this.fieldFail(element, msg);
                    return 1;
                } else {
                    this.fieldOk(element);
                    return 0;
                }
            } else {
                this.fieldFail(element, msg);
                return 1;
            }
        }
    };

    // validates date
    this.date_field = function (element, msg) {
        // flag to store errors for siblings
        var flag = 1;
        var checked_siblings = 0;
        element.siblings().each(function () {
            // if any field is empty and was checked before, set error
            if (self.checked_fields[$(this).attr("id")]) checked_siblings++;
            if ($(this).val() == "" && self.checked_fields[$(this).attr("id")]) {
                flag = 0;
            }
        });
        // if not all were selected yet, there is error but don't print it yet
        if (checked_siblings != 2) {
            return 1;
        } else if (flag && element.val()) {
            // all selected and no errors
            this.fieldOk(element);
            return 0;
        } else {
            this.fieldFail(element, msg);
            return 1;
        }
    };

    // validates login field
   
    this.login_field = function (element, expression, length, current, msg) {
        this.currentElement = element;

        this.currentMsg = msg;
        if (element.val() == "") {
            if (msg != "") msg = _("This field is required");
            this.fieldFail(element, msg);
            return 1;
        } else {
            if (element.val().length < length) {
                if (msg != "") msg = _("Must be at least")+" " + length +" "+_("characters long");
                this.fieldFail(element, msg);
                return 1;
            } else {
                if (! (element.val().match(expression))) {
                    if (msg != "") msg = _("Contains invalid characters")+"<br />"+_("Requirements")+": a-z, A-Z, 0-9, ., -, _";
                    this.fieldFail(element, msg);
                    return 1;
                } else {
                    // if current is not login field and was checked before (!=1), we will not run request
                    if (current.attr("id") != element.attr("id") && this.loginCheck > 0) {
                        // value 2 means previously field was validated as ok
                        if (this.loginCheck == 2) {
                            this.fieldOk(element);
                            return 0;
                        }
                        // value 3 means previously field was validated as false
                        if (this.loginCheck == 3) {
                            this.fieldFail(element, msg);
                            return 1;
                        }
                    }
                    this.ajaxRun = false;

   this.fieldOk(element);
                    // always return 0 , additional check in makeCall
                    return 0;
                }
            }
        }
    };


    // validates re-type field
    this.compare_repeats = function (field_1, field_2, expression, msg, msg2, length) {
        // check if not empty
        if (field_2.val() != '') {
            // bad format
            if (length != null && field_2.val().length < length) {
                this.fieldFail(field_2, _("Must be at least 6 characters long"));
                return 1;
            } else if (!field_2.val().match(expression)) {
                this.fieldFail(field_2, msg2);
                return 1;
                // fields do not match
            } else if (field_1.val() != field_2.val()) {
                this.fieldFail(field_2, msg);
                return 1;
                // everything ok
            } else {
                this.fieldOk(field_2);
                return 0;
            }
        } else {
            if (msg != "") msg = _("This field is required");
            this.fieldFail(field_2, msg);
            return 1;
        }
    };

    // handles display on correct field
    this.fieldOk = function (element) {


        if (!element) element = this.currentElement;
        if (this.checked_fields[element.attr("id")]) {
            element.parent().children("div.error-message").remove();
            element.next("span").removeClass("fail");
            element.next("span").addClass("accept");
        }
    };
    // handles display on wrong field	
    this.fieldFail = function (element, msg) {



        if (!element) element = this.currentElement;



        if (this.checked_fields[element.attr("id")]) {
            element.parent().children("div.error-message").remove();
            element.next("span").removeClass("accept");
            element.next("span").addClass("fail");
            if (msg == "") {

                element.parent().children("div.error-message").remove();
            } else {



                element.parent().append("<div class=\"error-message\"><div class=\"bg\"><div><p>" + msg + "</p></div></div><div class=\"bottom\"></div></div>");
                if (element.attr("id") != cur.attr("id")) {
                    element.parent().children("div.error-message").remove();
                } //here if problems
            };

        }
    };
    var cur;
    this.form = function (current) {
        this.errorCount = 0;
        this.ajaxRun = false;
        cur = current;
        var mark_check = true;
        // goes through all inputs
        this.inputs.each(function () {
            // if current element, add error message to display, otherwise reset it to empty
            if ($(this).attr("id") == current.attr("id")) {
                msg = self.messages[current.attr("id")];
                self.checked_fields[$(this).attr("id")] = 1;
            } else {
                // if we didn't loop over current (mark_check is still true), than set array element to 1
                if (mark_check) {
                    self.checked_fields[$(this).attr("id")] = 1;
                }

                ;
                msg = "";
            };
            switch ($(this).attr("id")) {
            case "q5201_q1":
               
               self.errorCount += self.login_field($(this), /^[a-zA-Z0-9_.-ÃŸÃ¤Ã¶Ã¼Ã„Ã–Ãœ&$*-]+$/, 6, current, msg);
                break;
            case "q5201_q3":
            case "q5201_q5":
            case "q5201_q6":
                self.errorCount += self.date_field($(this), msg);
                break;
			case "q5202_q4":
		                self.errorCount += self.standard_field($(this), /^[a-zA-Z0-9_#-ÃŸÃ¤Ã¶Ã¼Ã„Ã–Ãœ&$*]{6,}$/, msg, 6);
		                break;
            case "q5202_q4_2":
self.errorCount += self.compare_repeats($("#q5202_q4"), $(this), /^[a-zA-Z0-9_#-ÃŸÃ¤Ã¶Ã¼Ã„Ã–Ãœ&$*]{6,}$/, msg, self.messages["q5202_q4"], 6);
                break;
            case "q5202_q1":
self.errorCount += self.standard_field($(this), /^[a-zA-Z0-9-ÃŸÃ¤Ã¶Ã¼Ã„Ã–Ãœ&$*\s,]+$/, msg);
break;
            default:
                break;
            };
            // if loop is on currently checked, than set mark_check to false
            if ($(this).attr("id") == current.attr("id")) {
                mark_check = false;
            };
        });
        this.handleSubmitButton();
    };

    this.handleSubmitButton = function () {
        if (!this.errorCount) {
            if (!this.ajaxRun) {
                document.getElementById("form_email_5199_submit").disabled = false;
                $("#form_email_5199_submit").addClass("green");
                $("#form_email_5199_submit").parent('p').prev("div.arrow").addClass("arrow-green");
            }
        } else {
            document.getElementById("form_email_5199_submit").disabled = true;
            $("#form_email_5199_submit").removeClass("green");
            $("#form_email_5199_submit").parent('p').prev("div.arrow").removeClass("arrow-green");
        }
    };

} (jQuery);

/*search result rest asset (1647) translation*/
jQuery('#no_result_lang').html( _("No results were found") + ".");
jQuery('#result_lang').html( _("Search Results") );