/**
 * @author Damjee
 */
Vetstoria.usermenu = new(new Class({
    __construct: function () {

        this.buttons = [];
        this.logonfacebox = false;
        this.menu = '.usermenu .toplevel';
        this.menu_buttons_parent = '.usermenu .toplevel li ul';
        this.menu_buttons = this.menu_buttons_parent + ' li';

        this.user = '';
    },
    /**
	 * Contextual menu initialization
	 */
    init: function () {
        this.display();
    },
    /**
	 * Display the user menu
	 * @author Damjee
	 */
    display: function () {

        this.get_menu().hide();
		
        var user = Vetstoria.session.get();

        if (!user){
			this.add_content_no_session();
		}
        else if (user.type == 'petowner'){
        	var user = this.get_user_info();
            var username = user.firstname + " " + user.lastname;
			$('div#usermenu_click span#username').html(username);
			this.add_content_petowner();
	        this.add_content_universal();
	        this.get_menu().fadeIn();
		}
        else if (user.type == 'clinic'){
    	    if(Vetstoria.session.subsession_is_set()){
	            var subuser = this.get_subuser_info();
            	var subusername = subuser.forename + " " + subuser.surname;
				$('div#usermenu_click span#username').html(subusername);
				$('div#usermenu_click span#subtext').html((subuser.type_id==1?'Veterinarian':(subuser.type_id==2?'Nurse':'Support')));
				this.get_menu().fadeIn();
        	}
			this.add_content_clinic();
	        this.add_content_universal();
		}
    },
    /**
	 * Add clinic's action buttons to the menu
	 * @author Damjee
	 */
    add_content_clinic: function () {

        if(!Vetstoria.session.is_set()) return false;
        if(!Vetstoria.session.get().type == 'clinic') return false;

        //Subuser
        with(this) {
            get_menu_buttons_parent()
            .append(
                new_button(
                    'Switch User',
                    'clinic_subuser',
                    action_clinic_subuser,
                    'frontend/img/switch_user.png'
                    )
                )
            }
		
        with(this) {
        	get_menu_buttons_parent().append(new_button('Edit Profile', 'profile', action_profile))
		}
    },
    /**
	 * Add petowner's action buttons to the menu
	 * @author Damjee
	 */
    add_content_petowner: function () {
        console.log('Vetstoria.contextualmenu : adding petowner menu content');

        if(!Vetstoria.session.is_set()) return false;
        if(!Vetstoria.session.get().type == 'clinic') return false;
    },
    /**
	 * Add unlogged's action buttons to the menu
	 * @author Damjee
	 */
    add_content_no_session: function () {
				//Disabling cookie for saving username
				//var pref_identifier = $.trim($.cookie("Vetstoria.basic"));
                //var $form = $('<form><div class="input-boxes"><input type=text value="'+(pref_identifier==""?"Email":pref_identifier)+'" placeholder="Email"  class="login placeholder" /><input class="password-placeholder placeholder" value="Password" type=text placeholder="Password" /><input class=password style="display:none" type=password placeholder="Password" /><button type=submit >Login</button></div><div class="end-float"></div><div class="links"><div class="keep-logged"><input type=checkbox class=rememberme /> Keep me logged in</div><a href="./home/forgot" class="forgot-password no-text-shadow">Forgot password?</a></div></form>');
				//if(pref_identifier!="") $form.find('.login').removeClass('placeholder');
				
				var $form = $('<form><div class="input-boxes"><input name="email" type=text value="Email" placeholder="Email"  class="login placeholder" /><input class="password-placeholder placeholder" value="Password" type=text placeholder="Password" /><input class=password style="display:none" type=password placeholder="Password" /><button type=submit >Login</button></div><div class="end-float"></div><div class="links"><div class="keep-logged"><input type=checkbox class=rememberme /> Keep me logged in</div><a href="./home/forgot" class="forgot-password no-text-shadow">Forgot password?</a></div></form>');
               
                $form.find('.password').blur(function(){
                    if($(this).val()=="")
                    {
                        $form.find('.password-placeholder').show();
                        $form.find('.password-placeholder').val($form.find('.password-placeholder').attr('placeholder'));
                        $form.find('.password').hide();
                    }
                });
                $form.find('.password-placeholder').focus(function(){
                    $form.find('.password').show();
                    $form.find('.password-placeholder').hide();
                    $form.find('.password').focus();
                });
                $form.find('.login').blur(function(){
                    if($(this).val()=="")
                    {
                        $(this).val($(this).attr('placeholder'));
                        $(this).addClass('placeholder');
                        
                    }
                });
                $form.find('.login').focus(function(){
                    if($(this).val()==$(this).attr('placeholder'))
                    {
                        $(this).val('');
                        $(this).removeClass('placeholder');
                    }
                });
              
            
                $form.submit(function() {
				
                    login_email = $(this).find('input.login').val();
                    login_password = $(this).find('input.password').val();
                    login_remember = ($(this).find('input.rememberme').attr('checked'))?1:0;

                    if (login_email === undefined
                        || login_email === ""
                        || login_password === undefined
                        || login_password === "") {
							
                        console.log('login: an information is missing !')
                        return false;
                    }

                    var result = Vetstoria.session.login(login_email, login_password, login_remember);
						
                    if(result == false) {
                        $.msgbox("The Email or Password is incorrect. Please try again. ", {
                            type: "error",
                            buttons : [{
                                type: "submit",
                                value: "Ok"
                            }]
                        },function(){
							window.location.href = $BASE_PATH + 'home/forgot';
                            //Vetstoria.redirect('home/forgot','new message');
                        });
                    }
						
                    var user = Vetstoria.session.get();

                    if(user.type == 'clinic') Vetstoria.redirect('clinic');
                    if(user.type == 'petowner') Vetstoria.redirect('petowner');
						
                    return false;
                });
								
                $('.usermenu').append($form);
    },
    /**
	 * Add universal's action buttons to the menu
	 * @author Damjee
	 */
    add_content_universal: function() {
        console.log('Vetstoria.contextualmenu : adding universal menu content');
		
        with(this) {
            if (Vetstoria.session.is_set()) {
                get_menu_buttons_parent().append(new_button('My Settings', 'settings', action_settings));
                get_menu_buttons_parent().append(new_button('Logout', 'logout', action_logout));
            }
        }
		
    },
    /**
	 * Returns a jquery object corresponding
	 * @author Damjee
	 */
    get_menu: function () {
        return $(this.menu);
    },
    /**
	 * Returns a jquery object corresponding
	 * @author Damjee
	 */
    get_menu_buttons_parent: function () {
        return $(this.menu_buttons_parent);
    },
    /**
	 * Returns a jquery object corresponding
	 * @author Damjee
	 */
    get_buttons: function () {
        return $(this.menu_buttons);
    },
    /**
	 * Returns a jquery object corresponding
	 * @author Damjee
	 */
    get_button_by_classname: function (classname) {
        if (!classname || typeof classname != "string") return false;

        return this.get_buttons().filter('.' + classname);
    },
    /**
	 * Get the clinic team
	 * @author Damjee
	 */
    get_team: function (force) {

        // @todo : This should use Vetstoria.clinic.js
		
        if(!this.team || force) {
		
            this.team = [
            Vetstoria.json_command('clinic/data/team/types/get').data,
            Vetstoria.json_command('clinic/data/team/' + Vetstoria.session.get().id + '/get').data
            ];
		
        }
		
        return this.team;
    },
    /**
	 * @author Damjee
	 */
    get_user_info: function() {
        if(Vetstoria.session.get().type == 'clinic') {
            if(!this.user) {
                this.user = Vetstoria.json_command('clinic/data/informations/' + Vetstoria.session.get().id + '/get').data[0];
            }
            return this.user;
        }
        if(Vetstoria.session.get().type == 'petowner') {
            if(!this.user) {
                this.user = Vetstoria.json_command('petowner/data/get').data[0];
            }
            return this.user;
        }
        return false;
    },
    /**
	 * @author Damjee
	 */
    get_subuser_info: function () {
        if(Vetstoria.session.get().type == 'clinic') {
			
            if(!Vetstoria.session.subsession_is_set()) return false;
			
            var team = this.get_team();
            var user = Vetstoria.session.get_subuser();
            var cur = false;
			
            for(var i=0;i<team[1].length;++i) {
                cur = team[1][i];
                if(cur.id == user.id) {
                    return cur;
                }
            }
        }
        return false;
    },
    /**
	 * @author Damjee
	 */
    switch_subuser_facebox: function (_startup) {
        // display facebox, then json command switch subuser
        var count=0;
        var types = [];
        var clinicteam = this.get_team();

        //First clinic logins
        if(_startup && clinicteam[1]=="null"){
            $.facebox.settings.modal=true;
            Vetstoria.clinic.team.add_team_member_form(_startup);
            if(_startup){
                $('#facebox').hide();
                this.logonfacebox = true;
            }
            return;
        }

        var members = clinicteam[1];
        for(var i=0;i<clinicteam[0].length;++i){
            types[clinicteam[0][i].id]=clinicteam[0][i].name;
        }

        var maindiv = $('<div style="display:block;"/>');
        var container = $('<div style="display:block;width:638px;"/>').addClass('container');
		
        for(var i=0;i<members.length;++i){
            var content = $('<div id="'+ count +'" style="display:block;float:left;width:200px; "/>').addClass('cm_content member_plate').attr('rel',members[i].id).attr('name',(members[i].forename + " " +  members[i].surname).substr(0,20))
            .append($('<div />').append('<img src="'+ members[i].profile_picture +'" height="30px" width="30px" />').addClass('cm_imgbox'))
            .append($('<span class="message_head"/>').append((members[i].forename + " " +  members[i].surname).substr(0,20)).addClass('name'))
            .append('<br />')
            .append($('<span />').append(types[members[i].type_id]).addClass('content'))
            .append($('<div/>').addClass('end-float'));

            container.append(content);

            if(count>=(members.length-(members.length%3))) content.addClass('bottom');
            if(count%3==1) content.addClass('middle');

            ++count;
        }
        container.css("height",Math.ceil(count/3)*42);

        var prt = this;
        $(container).find('div.member_plate').click(function(){
            ret = Vetstoria.session.switch_subuser($(this).attr('rel'),'',true); 
            if(ret) {
                var subuser = prt.get_subuser_info();
				$('div#usermenu_click span#username').html((subuser.forename + " " +  subuser.surname).substr(0,20));
				$('div#usermenu_click img#avatar').attr("src",members[$(this).attr('id')].profile_picture);
				$('div#usermenu_click span#subtext').html((subuser.type_id==1?'Veterinarian':(subuser.type_id==2?'Nurse':'Support')));
				$('#toplevel').fadeIn();
                $.facebox.close();
				
				var path = String(window.location.href);
				if(path.indexOf('dashboard')>0){
					Vetstoria.feed.init();
				}
				else if(path.indexOf('pet')>0){
					window.location.reload();
				}
				else{
	                for(var j=0;j<types.length;++j){
    	                if(path.indexOf(types[j])>0){
        	                window.location.reload();
                	    }
                	}
				}
                //Restore facebox to normal
                $.facebox.settings.modal=false;
            }
        });
        maindiv.append('<div class="header text_left" style="margin-bottom:15px;"><h1 id="change_title">Select a Vet Practice User:</h1></div>');
        maindiv.append(container);

        if(_startup){
            //Set this to modal
            $.facebox.settings.modal=true;
        }
        $.facebox(maindiv);
        if(_startup){
            $('#facebox').hide();
            this.logonfacebox = true;
        }
    },
    /**
	 * @author Damjee
	 */
    new_button: function (name, classname, action, image) {

        if (action && typeof action != "function") action = false;

        var title = $('<div />');
        title.text(name);

        var button = $('<li />');
        button.addClass(classname);

        if (action) button.click(action);
        button.append(title);

        var ret = button.clone(true).hide().fadeIn();
        if (name=="") ret.hide();
        this.buttons.push(ret);

        return ret;
    },
    /**
	 * @author Damjee
	 */
	new_searchbar: function(){
		var button = $('<li class="search"><form class="expose" id="global_text_search" action="search" method="post"><input type="text" title="Type what you would like to find, here" class="click-hide-text search-box" value="Search Vetstoria" rel="Search Vetstoria" name="data[search_text]" /><input class="search-button" title="Search now" type="image" src="./frontend/img/search.png" /></form></li>');
        var ret = button.clone(true).hide().fadeIn();
        this.buttons.push(ret);
        return ret;
	},
    /**
	 * @author Damjee
	 */
    action: function ($button) {

        var session = Vetstoria.session.get();

        for (key in $button.attr('class').split(' ')) {

            switch (key) {
                default:
                    continue;
                    break;
                case "clinic_subuser":
                    this.action_clinic_subuser()
                    break;
                case "profile":
                    this.action_profile();
                    break;
                case "setting":
                    this.action_settings();
                    break;
                case "logout":
                    this.action_logout();
                    break;
            }
        }
    },
    /**
	 * @author Damjee
	 */
    action_clinic_subuser: function () {
        console.log('Vetstoria.contextualmenu : action_clinic_subuser launched');
        // Opens list of sub users to switch on
        Vetstoria.usermenu.switch_subuser_facebox(false);
    },
    /**
	 * @author Damjee
	 */
    action_login: function () {
        $.msgbox("<p >In order to login  you must provide the following (Or <a href='./home/forgot'>click here</a> if you have forgotton your password):</p>", {
            formaction: 'test',
            type: "prompt",
            inputs: [{
                type: "text",
                label: "Insert your Email address:",
                value: "",
                required: true
            },
            {
                type: "password",
                label: "Insert your Password:",
                required: true
            }],
            buttons: [{
                type: "submit",
                value: "OK"
            },
            {
                type: "cancel",
                value: "Exit"
            }]
        }, function (login_email, login_password) {

            var result = Vetstoria.session.login(login_email, login_password, true);

            if (login_email === undefined || login_email === "" || login_password === undefined || login_password === "") {
                console.log('Vetstoria.homepage.login: an information is missing !')
                return false;
            }

            if (result == false) {

                $.msgbox("An error occured with this login attempt. Do you want to try again?", {
                    type: "confirm",
                    buttons: [{
                        type: "submit",
                        value: "yes"
                    },
                    {
                        type: "submit",
                        value: "no"
                    }]
                }, function (result) {
                    if (result == 'yes') Vetstoria.contextualmenu.action_login();
                });

                return false;
            }

            var user = Vetstoria.session.get();

            var timeout = 5;

            $.msgbox("Login successful for <strong>" + login_email + "</strong>. Redirecting to your <strong>" + user.type + "</strong> profile in " + timeout + " seconds.", {
                type: "info"
            });

            if (user.type == 'clinic') setTimeout(function () {
                Vetstoria.redirect('clinic');
            }, timeout * 1000);
            if (user.type == 'petowner') setTimeout(function () {
                Vetstoria.redirect('petowner');
            }, timeout * 1000);

            return true;

        });
    },
    /**
	 * @author Damjee
	 */
    action_profile: function () {
        var user = Vetstoria.session.get();
		if (user.type == 'clinic'){
			var subuser = Vetstoria.usermenu.get_subuser_info();
			Vetstoria.redirect((subuser.type_id==1?'veterinarian':(subuser.type_id==2?'nurse':'support')) + "/" + subuser.id);
		}
    },
    /**
	 * @author Damjee
	 */
    action_settings: function () {
        var user = Vetstoria.session.get();
		if (user.type == 'petowner'){
        	var userdetails = Vetstoria.usermenu.get_user_info();
			Vetstoria.redirect("petowner/" + userdetails.id + "/edit");
		}
		else if (user.type == 'clinic'){
			var subuser = Vetstoria.usermenu.get_subuser_info();
			//Vetstoria.redirect((subuser.type_id==1?'veterinarian':(subuser.type_id==2?'nurse':'support')) + "/" + subuser.id);
			if(Vetstoria.clinic.team.team.length<=0){
				Vetstoria.clinic.team.team = Vetstoria.json_command('clinic/data/team/'+ Vetstoria.session.get().id +'/get').data;
			}
			
			var team = Vetstoria.clinic.team.team;
			var length = team.length;
			var index = 0;
			for(i=0;i<length;++i){
				if(team[i].id==subuser.id){
					index = i;
					break;
				}
			}
			Vetstoria.clinic.team.editMember(subuser.id, index, true);
		}
    },
    /**
	 * @author Damjee
	 */
    action_logout: function () {
        $.msgbox("You are about to logout... Are you sure ?", {
            type: "confirm",
            buttons: [{
                type: "submit",
                value: "Yes"
            },
            {
                type: "submit",
                value: "No !"
            }]
        }, function (result) {
            if (result == "Yes") {
                var json_data = Vetstoria.session.logout();
                if (json_data.state === "0") {
                    Vetstoria.redirect('home');
                }
            }
        });
    }
}));
