var LoggedIn = false;
var UserCommunityID = 0;
var UserName = "";
var InPlaceEditors = null;
var ActiveMenuItem = "home";
var Keyword = null;
var Shortcode = null;

window.onload=function(){
    Nifty("div#footer","all border");
    Nifty("div#banner-image-1","all fixed-height");
    Nifty("div#banner-image-2","all fixed-height");
    $('banner-image-2').setOpacity(0.0); 
    setTimeout("changeBannerImage(1)",5000);
    if ( Keyword && Shortcode ) {
        setActiveMenuItem("downloads");
    }
    else {
        setActiveMenuItem("home");
    }
}

function setKeywordShortcode(k,s)
{   
    Keyword = k;
    Shortcode = s;
}

function changeBannerImage(image)
{   
    var images = [
            ["banner-image-1-1.jpg","international calls and text"],
            ["banner-image-2-1.jpg","from anywhere..."],
            ["banner-image-2-2.jpg","...to anywhere"],
            ["banner-image-2-3.jpg","at a fraction of the normal cost"],
            ["banner-image-1-3.jpg","utilising innovative technology"]
    ];
    var backgroundURL = "url("+images[image][0]+")";
    var headerText = images[image][1];
    
    if ( $('banner-image-1').visible() ) {
        $('banner-image-2').setStyle({background: backgroundURL});
        $('banner-image-2-text').innerHTML = headerText;
        Effect.Fade('banner-image-1', { duration: 5.0 });
        Effect.Appear('banner-image-2', { duration: 5.0 });
    }
    else {
        $('banner-image-1').setStyle({background: backgroundURL});
        $('banner-image-1-text').innerHTML = headerText;
        Effect.Fade('banner-image-2', { duration: 5.0 });
        Effect.Appear('banner-image-1', { duration: 5.0 });
    }
    setTimeout("changeBannerImage("+(image>=(images.length-1)?0:image+1)+")",10000);
}

function setLeftPanelStyle(name)
{
    var backgroundURL = "'left panel background.jpg'";
    var title = "...";
    var width = 540;

    switch( name ) {
        case "home":
            backgroundURL = "'home panel background.jpg'";
            title = "Home";
            break;
        case "downloads":
            backgroundURL = "'download panel background.jpg'";
            title = "Download Roroa for FREE";
            break;
        case "sms":
            title = "Roroa SMS Version";
            break;
        case "pricing":
            title = "Topping Up and What it Costs";
            break;
        case "terms":
            title = "Terms and Conditions";
            break;
        case "contact":
            backgroundURL = "'contact panel background.jpg'";
            title = "Contact Us";
            break;
        case "profiles":
            title = "My Profile";
            break;
        case "editprofile":
            title = "Roroa Profile for \""+UserName+"\"";
            initEditProfilePanel();
            break;
        case "topup":
            title = "Roroa Credit Online Top-Up";
            break;
        case "login":
            title = "Roroa User Login";
            break;
    }
    
    $('left-panel').setStyle({background: 'url('+backgroundURL+')'});
    $('left-panel-content').setStyle({width: width+'px'});
    $('left-panel-title').innerText = title;
}

function setActiveMenuItem(name)
{
    if ( ActiveMenuItem == "editprofile" ) {
        releaseEditProfilePanel();
    }
    
    if ( name=="login") {
        if ( !LoggedIn ) {
            $('nav').childElements().each(function(e,i){e.className="";});
            ajax_loadContent("left-panel-content","login.asp?username=&password=&MSISDN=","setLeftPanelStyle('"+name+"');");
        }
    }
    else {
        ActiveMenuItem = name;
    
        if ( name=="forum" ) {
            window.open("forum/","_newTab");
        }
        else if ( name=="profiles") {
            $('nav').childElements().each(function(e,i){e.className="";});
            $(name).className="activelink";
            if ( LoggedIn ) {
                ajax_loadContent("left-panel-content","profiles.asp?ucid="+UserCommunityID,"setLeftPanelStyle('editprofile');");
            }
            else {
                ajax_loadContent("left-panel-content","login.asp?username=&password=&MSISDN=","setLeftPanelStyle('"+name+"');");
            }
        }
        else if ( name=="topup") {
            $('nav').childElements().each(function(e,i){e.className="";});
            $(name).className="activelink";
            if ( LoggedIn ) {
                ajax_loadContent("left-panel-content","topup.asp?ucid="+UserCommunityID,"setLeftPanelStyle('"+name+"');");
            }
            else {
                ajax_loadContent("left-panel-content","topup.asp?ucid=0&msisdn=&topup=0","setLeftPanelStyle('"+name+"');");
            }
        }
        else if ( (name=="downloads" || name=="pricing") && Keyword && Shortcode ) {
            $('nav').childElements().each(function(e,i){e.className="";});
            $(name).className="activelink";
            ajax_loadContent("left-panel-content",name+".asp?Keyword="+Keyword+"&Shortcode="+Shortcode,"setLeftPanelStyle('"+name+"');");
        }
        else {
            $('nav').childElements().each(function(e,i){e.className="";});
            $(name).className="activelink";
            ajax_loadContent("left-panel-content",name+".asp","setLeftPanelStyle('"+name+"');");
        }
    }
}

function MenuSelect( menuAnchor, style ) 
{
    var item = $(menuAnchor.parentNode).identify();
    
    setActiveMenuItem(item);
}

function popUpMessageBox(title, message)
{
    showPopUp("messagebox",title,message,"modal mask:white;");
}

function validateRegisterForm(myForm, Shortcode, Keyword) {
	var valid = false;
	var msisdn = String(myForm.msisdn.value);
	var numericPattern = /^(\+|\d)[\d]*$/;
	if (numericPattern.test(msisdn) == true) {
		if (msisdn.substr(0, 4) == "+447" && msisdn.length == 13) {
            msisdn = msisdn.substr(1);
			valid = true;
		}
		if (msisdn.substr(0, 3) == "447" && msisdn.length == 12) {
			valid = true;
		}
		else if (msisdn.substr(0, 2) == "07" && msisdn.length == 11) {
            msisdn = "44"+msisdn.substr(1);
			valid = true;
		}
	}
	if (valid) {
        ajax_loadContent("left-panel-content","downloads.asp?Shortcode="+Shortcode+"&Keyword="+Keyword+"&MSISDN="+msisdn);
	}
	else {
	    popUpMessageBox("Error", "Invalid entry, please enter your full mobile number in the form \"07123456789\" or \"+447123456789\".")
	}

	return(false);
}

function Login()
{
    if ( LoggedIn ) {
        LoggedIn = false;
        $('login').innerText = "Login";
        $('login-user').innerText = "";
        UserCommunityID = 0;
        UserName = "";
    }
    setActiveMenuItem('login');
}

function LoginUser(username, usercommunityid)
{
    LoggedIn = true;
    $('login').innerHTML = "Logout";
    $('login-user').innerHTML = "Logged in as:<b>"+username+"</b>";
    UserCommunityID = usercommunityid;
    UserName = username;
    setActiveMenuItem(ActiveMenuItem);
    setLeftPanelStyle(ActiveMenuItem);
}

function validateLoginForm(myForm) {
	var valid = false;
	var msisdn = String(myForm.msisdn.value);
	var username = String(myForm.username.value);
	var password = String(myForm.password.value);
	
	var numericPattern = /^(\+|\d)[\d]*$/;
	if (numericPattern.test(msisdn) == true) {
		if (msisdn.substr(0, 1) == "+") {
            msisdn = msisdn.substr(1);
		}
		else if (msisdn.substr(0, 2) == "07" && msisdn.length == 11) {
            msisdn = "44"+msisdn.substr(1);
		}
	    valid = true;
	}
	if (valid) {
        ajax_loadContent("left-panel-content","login.asp?username="+username+"&password="+password+"&MSISDN="+msisdn);
	}
	else {
	    popUpMessageBox("Error", "Invalid entry, please enter your full mobile number in the form \"07123456789\" or \"+447123456789\".")
	}

	return(false);
}

function initEditProfilePanel()
{
    Event.observe($('avatar-selected-image'), 'click',  onClickField);
    Event.observe($('avatar-selected-image'), 'mouseover', highLightField);
    Event.observe($('avatar-selected-image'), 'mouseout',  endHighLightField);
    
    InPlaceEditors = new Array();
    InPlaceEditors.push(new Ajax.InPlaceEditor('first_name', 'updateprofile.asp',{callback: function(form, value) { return 'ucid='+UserCommunityID+'&value='+encodeURIComponent(value); }, okControl:"button",cancelControl:"button",okText:"Ok",cancelText:"X",highlightcolor:"#00AA01",highlightendcolor:"#C927C9"}));
    InPlaceEditors.push(new Ajax.InPlaceEditor('last_name', 'updateprofile.asp',{callback: function(form, value) { return 'ucid='+UserCommunityID+'&value='+encodeURIComponent(value); }, okControl:"button",cancelControl:"button",okText:"Ok",cancelText:"X",highlightcolor:"#00AA01",highlightendcolor:"#C927C9"}));
    InPlaceEditors.push(new Ajax.InPlaceEditor('country', 'updateprofile.asp',{callback: function(form, value) { return 'ucid='+UserCommunityID+'&value='+encodeURIComponent(value); }, okControl:"button",cancelControl:"button",okText:"Ok",cancelText:"X",highlightcolor:"#00AA01",highlightendcolor:"#C927C9"}));
    InPlaceEditors.push(new Ajax.InPlaceEditor('city_town', 'updateprofile.asp',{callback: function(form, value) { return 'ucid='+UserCommunityID+'&value='+encodeURIComponent(value); }, okControl:"button",cancelControl:"button",okText:"Ok",cancelText:"X",highlightcolor:"#00AA01",highlightendcolor:"#C927C9"}));
    InPlaceEditors.push(new Ajax.InPlaceEditor('notes', 'updateprofile.asp',{callback: function(form, value) { return 'ucid='+UserCommunityID+'&value='+encodeURIComponent(value); }, okControl:"button",cancelControl:"button",okText:"Ok",cancelText:"X",highlightcolor:"#00AA01",highlightendcolor:"#C927C9",rows:4,cols:34}));
}

function releaseEditProfilePanel()
{
    if ( $('avatar-selected-image')!=null ) {
        Event.stopObserving($('avatar-selected-image'), 'click',  onClickField);
        Event.stopObserving($('avatar-selected-image'), 'mouseover', highLightField);
        Event.stopObserving($('avatar-selected-image'), 'mouseout',  endHighLightField);
    }
    if ( InPlaceEditors != null ) {
        for ( var i=0;i<InPlaceEditors.length;i++ ) {
            InPlaceEditors[i].dispose();
        }
    }
}

function highLightField(event)
{
    var element = Event.element(event); 
    $(element.parentNode).setStyle({ background: '#00AA01' });

}

function endHighLightField(event)
{
    var element = Event.element(event); 
    new Effect.Highlight($(element.parentNode), { startcolor: '#00AA01',endcolor: '#C927C9', restorecolor: 'white', keepBackgroundImage: true });
}

function onClickField(event)
{
    var element = Event.element(event); 
    if ( $(element).identify() == "avatar-selected-image" ) {
        popUpAvatarPicker(UserCommunityID);
    }
}

function popUpAvatarPicker(UserCommunityID)
{
    createPopUp("avatar-picker","Select an Avatar","Here you can change and upload your Avatar.","modal mask:white;");
    ajax_loadContent("avatar-picker-content","avatarpicker.asp?ucid="+UserCommunityID,"realiseAvatarPicker()");
}

function realiseAvatarPicker()
{
    Nifty("div.avatar-list-item","all fixed-height");
    realisePopUp("avatar-picker","modal nodrag");
}

function selectAvatar(URL,UserCommunityID)
{
    $('avatar-selected-image').setStyle({background: 'url(ajax-loader.gif)'});
    closePopUp();
    new Ajax.Request("updateprofile.asp", {
        parameters: { editorId:'avatarURL', value: URL, ucid: UserCommunityID },
        onSuccess: function(transport) {
            var response = transport.responseText;
            var backgroundURL = "'http://wap.m-quest.co.uk:8020/imgresize/?w=64&h=64&t=jpg&u="+encodeURIComponent(response)+"'";
            $('avatar-selected-image').setStyle({background: 'url('+backgroundURL+')'});
        }, 
        onFailure: function(transport) {
            alert(transport.responseText);
        } 
    });     
}    

function uploadAvatar(UserCommunityID)
{
    popUpAvatarUploader(UserCommunityID);
}

function popUpAvatarUploader(UserCommunityID)
{
    createPopUp("avatar-upload","Upload an Avatar","Here you can change and upload your Avatar.","modal mask:white;");
    ajax_loadContent("avatar-upload-content","uploadavatar.asp?ucid="+UserCommunityID,"realiseAvatarUploader()");
}

function realiseAvatarUploader()
{
    realisePopUp("avatar-upload","modal nodrag");
}

function validateTopupForm(myForm, UserCommunityID, VATRate) {
	var valid = false;
	var topup = Number(myForm.amount.value);
	var msisdn = String(myForm.msisdn.value);
	
	var amount = (topup*100.0)/(100.0+VATRate);
	amount = Math.round(amount*100)/100.0;
	var tax = topup-amount;
	tax = Math.round(tax*100)/100.0;

	var numericPattern = /^(\+|\d)[\d]*$/;
	if (numericPattern.test(msisdn) == true) {
		if (msisdn.substr(0, 1) == "+") {
            msisdn = msisdn.substr(1);
		}
		else if (msisdn.substr(0, 2) == "07" && msisdn.length == 11) {
            msisdn = "44"+msisdn.substr(1);
		}
	    valid = true;
	}

    if ( valid ) {
        ajax_loadContent("left-panel-content","topup.asp?ucid="+UserCommunityID+"&msisdn="+msisdn+"&topup="+topup);
    }
	else {
	    popUpMessageBox("Error", "Invalid entry, please enter your full mobile number in the form \"07123456789\" or \"+447123456789\".")
	}

    //createPopUp("topup-payment","Top Up Payment","Here you pay online for your top up.","modal mask:white;");
    //ajax_loadContent("topup-payment-content","topuppayment.asp?ucid="+UserCommunityID+"&a="+amount,"realisePopUp(\"topup-payment\",\"modal nodrag\")");

    //window.open("https://www.m-quest.co.uk/roroa.com/paypalsubmit.asp?ucid="+UserCommunityID+"&amount="+amount+"&tax="+tax+"&description=Roroa Account Top Up","_newTab");
    //window.open("http://m-quest-app3/roroa.com/paypalsubmit.asp?ucid="+UserCommunityID+"&amount="+amount+"&tax="+tax+"&description=Roroa Account Top Up","_newTab");

	return(false);
}


