Vetstoria.layout = new (new Class({

    __construct: function(){
        
    },
    
    init: function(){
        
        console.log('Vetstoria.layout:', 'init');
        this.check_browser();
        this.vetstoria_ui();
        this.show_upload_link();
        
        // @kaveen, display elements with the class 'logged' when the user has logged in
        if(Vetstoria.session.get().id)
        {
            $('.logged').css('display','inline');
            $('.logged').css('visibility','visible');
        }
        else{
            $('.logged').css('display','none');
            $('.logged').css('visibility','hidden');
        }
        // @kaveen, hide text when the input box is clicked on
        $('input.click-hide-text').click(function(){
            if($(this).val()==$(this).attr('rel')) $(this).val("");
        });
        $('input.click-hide-text').blur(function(){
            if($(this).val()=="") $(this).val($(this).attr('rel'));
        });

        // @kaveen, functions which needs to be executed for each page are placed here
        //        setInterval((function(){
        //            // @kaveen, tooltip initialization
        //            ////////////////////////////////
        //            $("*[title]").tooltip({
        //                events: {
        //                    def:     "mouseenter,mouseleave",    // default show/hide events for an element
        //                    input:   "mouseenter,mouseleave",               // for all input elements
        //                    widget:  "mouseenter,mouseleave",  // select, checkbox, radio, button
        //                    tooltip: "mouseenter,mouseleave"     // the tooltip element
        //                },
        //                effect:'slide',
        //                delay:0,
        //                predelay:300
        //            });
        //            // @kaveen, replace broken image with a defualt image
        ////            $('img').error(function(){
        ////                $(this).attr('src', './frontend/img/no_image.png');
        ////            });
        //        ////////////////////////////////
        //        }),100);
        
        // @kaveen, expose the form when it's clicked or cursor is focused
        //        $(".body form, .expose").bind("click keydown", function() {
        //            $(this).expose({
        //
        //                // when exposing is done, change form's background color
        //                onLoad: function() {
        //                    $('.expose-message').fadeIn('slow');
        //                },
        //                closeSpeed: 'fast',
        //                openSpeed: 'fast',
        //                // when "unexposed", return to original background color
        //                onClose: function() {
        //                    $('.expose-message').fadeOut('slow');
        //                }
        //
        //            });
        //        });
        // @kaveen, closing the background mask on button click
        //        $(".body form button, .body form input[type=button], .body form input[type=submit], .expose button, .expose input[type=submit], .expose input[type=button]").bind("click keydown", function() {
        //            $('#exposeMask').fadeOut('slow');
        //            $('.expose-message').fadeOut('slow');
        //        });
        // @kaveen, adds the class "selected" to the current link
        var fragment = window.location;
        $('a[href=' + fragment + ']').addClass('selected');
        
        // @kaveen, initialize scrollable with mousewheel support (vertical)
        $(".scrollable").scrollable({
            vertical: true,
            mousewheel: true
        });
        // @kaveen, initialize scrollable with mousewheel support (horizontal)
        $(".scrollable-horizontal").scrollable({
            mousewheel: true
        });
        
        // @kaveen, tab setup for pet member search
        // setup ul.tabs to work as tabs for each div directly under div.panes
        $("ul.pet-member-tabs").tabs("div.pet-member-panes > div", {
            effect: 'fade',
            fadeOutSpeed: 400
        });
        

        
        // @kaveen, inputbox effects
        /*
        $('input[type=text],input[type=password],textarea').mouseenter(function(){
            $(this).animate({
                backgroundColor: '#E6F6FA',
                borderColor: '#24A6CA',
                color: '#000000'
            }, 500, function() {
                // Animation complete.
                });
        });
        $('input[type=text],input[type=password],textarea').mouseout(function(){
            $(this).animate({
                backgroundColor: '#ffffff',
                borderColor: 'none',
                color: '#555555'
            }, 500, function() {
                // Animation complete.
                });
        });
         */
        
        // @kaveen, Initialize facebox
        $('a[rel*=facebox]').facebox();
        
        //This prototype is provided by the Mozilla foundation and
        //is distributed under the MIT license.
        // @kaveen, the javascript array filter function is not implemented in IE and this function would act as a suppliment.
        //http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
       
        if (!Array.prototype.filter)
        {
             
            Array.prototype.filter = function(fun /*, thisp*/)
            {
                try{
                    var len = this.length;
                    if (typeof fun != "function")
                        throw new TypeError();

                    var res = new Array();
                    var thisp = arguments[1];
                    
                    for (var i = 0; i < len; i++)
                    {
                        if (i in this)
                        {
                            var val = this[i]; // in case fun mutates this
                            if (fun.call(thisp, val, i, this))
                                res.push(val);
                        }
                    }

                    return res;
                }
                catch (er)
                {}
            };
        }
        //	this.varia();

        $('form#global_text_search').submit(function() {
            if($(this).find('input#search_text').val().length<2){
                $.msgbox("Minimum of two search characters are required!", {
                    type: "info"
                });
                return false;
            }
        })
        // @kaveen, call breadcrumbs
        this.breadcrumbs();
        // @kaveen, calling tabheightfix
        //        $(document).ready(function(){
        //            setTimeout('Vetstoria.layout.tabHeightFix()',300);
        //        });
        // @kaveen, shows the toolbar on mouse over
        this.show_toolbar();
        //$(document).ready(function(){
        //    setInterval(function(){
        //        Vetstoria.layout.tabHeightFix();
        //    },100);
        Vetstoria.layout.tabHeightFix();
        // @kaveen, the resize event causes problems in IE
        if(navigator.userAgent.toLowerCase().indexOf('msie')==-1)
            $(window).resize(function(){
                Vetstoria.layout.tabHeightFix();
            })
        
        //  @kaveen, enabling breadcrumbs for profile pages
        /*
        if($('.body > div > div').hasClass('profile'))
        {
            $('.bread-crumbs').show();
        }
            */
       
        /* ========== */
        //});
        // @kaveen, placeholder initialization
        $(':input:not([type=submit])').placeholder();
        // @kaveen, lateral scroll quick fix
        $('.body > .body-width').scroll(function(){
            $(this).scrollLeft(0)
        });
    },
    components: {
    
        //Create a new card and return it
        card: function(type, img_url, name, options){
        
            var settings = {
                owner_name: '',
                owner_url: '',
                meta: ['']
            }
            
            
            return $();
        },
        
        //Create a new panel and return it
        content: function(){
        
        },
        
        //Create a new panel and return it
        panel: function(type, title, columns){
        },
        
        //Create a new panel and return it
        block: function(type, title, columns){
        }
    },
    show_toolbar:function(){
        $('.ui.card.mini').hover(function(){
            $(this).find('.toolbar').show();
        },
        function(){
            $(this).find('.toolbar').hide();
        }
        );
    //        $('.ui.card.mini').mouseout(function(){
    //            $(this).find('.toolbar').hide();
    //        });

    },
    alert: function(content){
        $.msgbox(content);
    },
    escape_characters: function(str){
        return str.replace(/[#;&,\.\+\*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\$&');
    }
    ,
    modal_box: function(content){
        console.log(content);
    },
    
    modal_box_confirm: function(content){
        console.log(content);
    },
    
    modal_box_error: function(content){
        console.log(content);
    },
    
    vetstoria_ui: function(){
    
        console.log('Vetstoria.layout.vetstoria_ui: called')
    	
        // Not perfect, but it works. We will replace this by an abstraction layer placed in vetstoria.layout asap.
        //        setInterval((function(){
        //            //$('button, input[type=submit], input[type=button]').not('.ui-button').button();
        //            $('div.locked, input[type=submit].locked, input[type=button].locked').not('.ui-button-text-icon').button({
        //                icons: {
        //                    primary: 'ui-icon-locked'
        //                }
        //            });
        //        }), 100);
        
        //tab widget
        // @kaveen, tab event handler
        $('*').click(function(){
            if(!$.cookie("PHPSESSID"))
            {
                window.location='./register';
                return;
            }
            
        });

        /*
        $.address.change(function(event){
            alert($.address.state());
        });
        $('#contextualmenu .submenutitle').click(function(){
            $.address.value($(this).text());

        });*/
        
        $('div.tabs > div').click(function(){
            $('.formError').remove(); // @kaveen, remove validation popups on tab switch
            Vetstoria.layout.tabHeightFix();
        });
        $('input').click(function(){
            //if(!$(this).attr('onClick').match(/(javascript:location.href)/g))
            //{
            if($(this).attr('onClick'))
                Vetstoria.layout.tabHeightFix();
        //}
        });
        $('button').click(function(){
            //if(!$(this).attr('onClick').match(/(javascript:location.href)/g))
            //{
            //    Vetstoria.layout.tabHeightFix();
            //}
            });
        $('a').click(function(){
            if($(this).attr('href')=='javascript:;'||$(this).attr('href')=='javascript:void(0)'||$(this).attr('href')=='javascript:void(0)'||!$(this).attr('href'))
            {
                if (!$(this).hasClass('horizontal'))
                {
                    Vetstoria.layout.tabHeightFix();
                }
            }
        });
        $('.contentRow').click(function(){
            Vetstoria.layout.tabHeightFix();
        });
      
        $('.tabbed > .tabs > div').click(function(){
           
            if(!$(this).hasClass('disabled')){
                
                var tabs = $(this).parents('.tabbed').find('.tab-pane'), buttons = $(this).parent().find('div'), index = buttons.index(this), reg_init = new RegExp("(init:([A-z0-9\.]*))", "g"), to_initialize = $(this).attr('class').match(reg_init);
            
                if (to_initialize) {
                    for (var i = 0; i < to_initialize.length; i++) {
                        to_initialize[i].replace(/init:/g, '');
                    
                        if (eval(to_initialize[i]).init)
                            eval(to_initialize[i]).init(tabs.eq(index));
                    }
                }
                tabs.hide().eq(index).fadeIn();
            
                buttons.removeClass('selected').eq(index).addClass('selected');
                Vetstoria.layout.breadcrumbs();
                
                

            }
            

                
            
        })
        $('.tabbed').each(function(){
            $(this).find('.tabs > div').eq(0).click();
        });
        
        this.show_menu();
        
        
    },
	addtoAddressHash: function(hash){
		$.address.value($.address.value+'/'+hash);
	},
	setAddressHash: function(hash){
		$.address.value('/'+hash);
	},
    // @kaveen, sticky footer script


    //    positionFooter: function (){// @kaveen, Keep the footer at the bottom when the page height is less than the screen height
    //        if($('body').height() < $(window).height()){
    //            $("body > div.footer").css({
    //                position: "absolute",
    //                top:($(window).scrollTop()+$(window).height()-$("body > div.footer").height())+"px"
    //            })
    //        }
    //        else{
    //            $("body > div.footer").css({
    //                position: "relative",
    //                top:"0px"
    //            })
    //        }
    //        $(window)
    //        .scroll(Vetstoria.layout.positionFooter)
    //        .resize(Vetstoria.layout.positionFooter)
    //},
    tabHeightFix: function(){// @Kaveen, keep the tab pane height touch the footer at all times
    /*
        $('body > .footer').hide();
        
        function set_height(){

            var IEoffset=0;
            var documentOffset=0;
            if(navigator.userAgent.toLowerCase().indexOf('msie')!=-1)
            {
                IEoffset =document.documentElement.scrollTop;
                documentOffset=-4;
            }
            var footer_border_width=parseInt($('body > .footer').css('borderTopWidth').replace('px',''));
            if($('.glass-pane .tab-pane > div').height()!=null)
            {
                $.each($('.glass-pane .tab-pane > div'),function(index){

                    if($(this).height()>0&&$(this).css('display')=='block'){
                        var padding_bottom=parseInt($(this).parent().css('paddingBottom').replace('px',''));
                        
                        $(this).css('height','auto');
                        if((($(this).offset().top+$(this).height()+padding_bottom+$('body > .footer').height()+footer_border_width)>$(window).height())&&
                            (($(this).offset().top+$(this).height()+padding_bottom+$('body > .footer').height()+footer_border_width)>($('.small-column').height()+$('.small-column').offset().top+$('body > .footer').height()+footer_border_width)))
                            {
                            return;
                        }
                        if(($(document).height()+documentOffset)>$(window).height())
                        {
                            $(this).height(($(document).height()+documentOffset)-IEoffset-$(this).offset().top-$('body > .footer').height()-footer_border_width-padding_bottom);
                        }
                        else
                        {
                            $(this).height($(window).height()-IEoffset-$(this).offset().top-$('body > .footer').height()-footer_border_width-padding_bottom);
                        }
                    }
                });
            }
            else
            {
                
                if (($('body').height()+$('body > .footer').height()+footer_border_width)<$(window).height())
                {
                    $('body > .footer').css('top',($(window).height()-$('body > .footer').height()-footer_border_width-($('.body').offset().top+$('.body').height()))+'px');
                }
            }
        }      
        function show_footer(){
            $("body > .footer").fadeIn('fast');
        }
        var interval=null;
        function clear_interval()
        {
            clearInterval(interval);
        }
        $(document).ready(function(){
            
            interval = window.setInterval(set_height,100);
   
            setTimeout(show_footer,100);
            setTimeout(clear_interval,1000);
        });
        */
    },
    breadcrumbs: function(path){
        // @kaveen, Bread-crumbs feature
        var breadcrumbs = $('.bread-crumbs');
        var top_menu_path = $('.body-container > .header .menu ul li a')
        var content_tab_path = $('.large-column .tabs > div, .glass-pane > .widget .tabs > div');
        var my_profile = 0;
        breadcrumbs.html('<a href="./" title="Go back to the homepage" >Home</a>');


        $.each(top_menu_path,function(data){
            if(top_menu_path.eq(data).hasClass('selected'))
            {
                breadcrumbs.append(' <span>&gt;</span> <a href="'+top_menu_path.eq(data).attr('href')+'" title="'+top_menu_path.eq(data).text()+'" >'+top_menu_path.eq(data).text()+'</a>');
                if(top_menu_path.eq(data).text()=='My Profile')
                    my_profile=1;
            }

        });
        if(!my_profile&&$('.two-column-mainpage  .small-column > h1, .glass-pane > h1').text())
            breadcrumbs.append(' <span>&gt;</span> '+$('.two-column-mainpage  .small-column > h1, .glass-pane > h1').text());
        $.each(content_tab_path, function(data){
            if(content_tab_path.eq(data).hasClass('selected'))
            {
                breadcrumbs.append(' <span>&gt;</span> '+content_tab_path.eq(data).text()+'');
            }
        });
       
        
    },
    /**
 * This function allow you to define some parameters in the class attribute of your html element
 * Example :
 * 		<a class="my_param:true" id="my_id" />
 * 		var parameter = Vetstoria.layout.get_class_param($('#my_id'), 'my_param');
 */
    get_class_param: function($element, param){
    
        function str_replace(search, replace, subject, count){
            var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0, f = [].concat(search), r = [].concat(replace), s = subject, ra = r instanceof Array, sa = s instanceof Array;
            s = [].concat(s);
            if (count) {
                this.window[count] = 0;
            }
            for (i = 0, sl = s.length; i < sl; i++) {
                if (s[i] === '') {
                    continue;
                }
                for (j = 0, fl = f.length; j < fl; j++) {
                    temp = s[i] + '';
                    repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
                    s[i] = (temp).split(f[j]).join(repl);
                    if (count && s[i] !== temp) {
                        this.window[count] += (temp.length - s[i].length) / f[j].length;
                    }
                }
            }
            return sa ? s : s[0];
        }
        
        
        var pattern = new RegExp("(" + param + ":([A-z0-9\.]*))", "g"), matches = $(element).attr('class').match(pattern);
        
        if (matches) {
            for (var i = 0; i < matches.length; i++) {
                str_replace(param, matches[i]);
            }
        }
        
        return matches;
    },
	
    show_upload_link: function(){
    
        var $profilePicture = $("div.profile-picture"), $link = $("div.profile-picture .change");
        $link.hide();
        
        $profilePicture.hover(function(){
            $link.show();
        }, function(){
            $link.hide();
        });
        
    //        $link.hover(function(){
    //            $link.stop().animate({
    //                "opacity": 1
    //            })
    //        }, function(){
    //            $link.stop().animate({
    //                "opacity": 0.5
    //            })
    //        });
		
    },
	
    varia: function(){
        
        $('#header .feedback > b[title]').qtip({
            style: {
                name: 'dark',
                tip: true
            },
            position: {
                corner: {
                    target: 'leftMiddle',
                    tooltip: 'rightMiddle'
                }
            }
        });
        
        $("#toggle_select_team").click(function(){
            var clinic_id = $(this).attr('rel');
            $.facebox({
                ajax: $BASE_PATH + 'clinic/select/' + clinic_id
            });
            return false;
        });
        
        $("#send_feedback").click(function(){
            $.facebox({
                ajax: $BASE_PATH + 'bugs'
            });
            return false;
        });
    },
    
    check_browser: function(){
    
        var userBrowser = {};
        var ua = navigator.userAgent.toLowerCase();
        
        var browser;
        (browser = ua.match(/msie ([\d.]+)/)) ? userBrowser.ie = browser[1] : (browser = ua.match(/firefox\/([\d.]+)/)) ? userBrowser.firefox = browser[1] : (browser = ua.match(/chrome\/([\d.]+)/)) ? userBrowser.chrome = browser[1] : (browser = ua.match(/opera.([\d.]+)/)) ? userBrowser.opera = browser[1] : (browser = ua.match(/version\/([\d.]+).*safari/)) ? userBrowser.safari = browser[1] : 0;
        
        if (userBrowser.ie) {
            var version = userBrowser.ie.split(".")
            console.log('Vetstoria.layout:', 'browser version', version[0]);
            if (version[0] < 8) {
                Vetstoria.redirect("update_browser");
            }
            
        }
        
        if (userBrowser.firefox) {
            var version = userBrowser.firefox.split(".")
            console.log('Vetstoria.layout:', 'browser version', version[0]);
            if (version[0] < 3) {
                Vetstoria.redirect("update_browser");
            }
            
        }
        if (userBrowser.chrome) {
            var version = userBrowser.chrome.split(".")
            console.log('Vetstoria.layout:', 'browser version', version[0]);
            if (version[0] < 3) {
                Vetstoria.redirect("update_browser");
            }
            
        }
        if (userBrowser.opera) {
            var version = userBrowser.opera.split(".")
            console.log('Vetstoria.layout:', 'browser version', version[0]);
            if (version[0] < 9) {
                Vetstoria.redirect("update_browser");
            }
            
        }
        if (userBrowser.safari) {
            var version = userBrowser.safari.split(".")
            console.log('Vetstoria.layout:', 'browser version', version[0]);
            if (version[0] < 3) {
                Vetstoria.redirect("update_browser");
            }
            
        }
        //$('body, html').css('visibility','visible');
        return true;
    },
	
    /**
 * @todo : remove ! Because : 1/ It depends  on the session only, it's not possible anylonger. 2/ Name non explicit
 */
    display_login_msg:function(type){
	
        console.log('Vetstoria.layout.display_login_msg')
        return;
    	
        var $main_menu = $("#main_menu li");
		
        if(type=="clinic"){
            $main_menu.show();
            $main_menu.eq(0).hide();
            $main_menu.eq(1).hide();
            $main_menu.eq(4).hide();
            $main_menu.eq(5).hide();
        }else if(type =="petowner"){
            $main_menu.show();
            $main_menu.eq(0).hide();
            $main_menu.eq(1).hide();
            $main_menu.eq(2).hide();
            $main_menu.eq(3).hide();
        }else{
            $main_menu.hide();
            $main_menu.eq(0).show();
            $main_menu.eq(1).show();
            $main_menu.eq(6).show();
            $main_menu.eq(7).show();
            $main_menu.eq(8).show();
        }
		
    },
	
    /**
 * Show different elements in the menu depending on the window location and the session
 * @notice : not finished
 */
    show_menu: function(){
		
        console.log('Vetstoria.layout.show_menu called');
		
        //return;
		
        var url = window.location.pathname,
        menu = $("#main_menu li a"),
        op, subop, available_links, selected_link;
			
        url = url.split("/");
		
        op = url[1];
        subop = url[2];

        // @Charaf - we wil have to do this using the logged in user type rather than the URL because for example
        //          a petowner can access the clinic profile, but still needs the 'My Profile' on the menu

        switch(subop) {
            //            case "profile":
            //                available_links = ['my_profile_petowner', 'available_clinics', 'available_petowners'];
            //                selected_link = ['my_profile_petowner'];
            //                break;

            default:
                if (Vetstoria.session.user.type=='petowner')
                {
                    available_links = ['my_profile_petowner', 'available_clinics', 'available_petowners'];
                //selected_link = ['my_profile_petowner'];
                    
                }
                else if(Vetstoria.session.user.type=='clinic')
                {
                    available_links = ['my_profile_clinic', 'available_clinics', 'available_petowners'];
                }
                else
                    available_links = ['available_clinics', 'available_petowners'];
                //selected_link = ['home'];
                break;
        /**
			case "clinic":
				available_link = ['my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
			case "clinics":
				available_link = ['petowner_signup', 'vet_signup', 'my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
			case "community":
				available_link = ['petowner_signup', 'vet_signup', 'my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
			case "pet":
				available_link = ['petowner_signup', 'vet_signup', 'my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
			case "profile":
				available_link = ['petowner_signup', 'vet_signup', 'my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
			case "veterinarian":
				available_link = ['petowner_signup', 'vet_signup', 'my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
			case "register":
				available_link = ['petowner_signup', 'vet_signup', 'my_clinic', 'my_profile_clinic', 'my_profile_petowner', 'available_clinics', 'available_petowners'];
			break;
         **/
        }

        for(var i=0;i<available_links.length;i++) {
			
            console.log('Vetstoria.show_menu: enabling', i, '#main_menu li.' + available_links[i])
            $('#main_menu li.' + available_links[i]).fadeIn();
        }
	    
        //Always available
        $('#main_menu li.search').fadeIn();
		
        /*
 * Link selection
 */
        var index=1;
        if(url[1]=='vetstoria')// @kaveen, to fix a problem when running the system on localhost
        {
            index=2;
        }
        if(url[index]=="register"){
            if(url[index+1]=="petowner"){
                menu.eq(0).addClass("selected");
            }else if(url[index+1]=="clinic"){
                menu.eq(1).addClass("selected");
            }
        }else if(url[index]=="clinics"){
            menu.eq(6).addClass("selected");
        }else if(url[index]=="community"){
            menu.eq(7).addClass("selected");
        }else if(url[index]=="clinic"){
            menu.eq(4).addClass("selected");
        }else if(url[index]=="veterinarian"){
            menu.eq(3).addClass("selected");
        }else if(url[index]=='profile'){
        //menu.eq(4).addClass("selected");
        }else if(url[index]=="pet"){
    //menu.eq(5).addClass("selected");
    }
    }
}));
 
