﻿// Class for boutique actions
// getting user data for "Meine Lebensart"
// showing interests for each user
// received json structure:

/*---------------------------------------------- My Lebensart -------------------------------------------*/
var BoutiqueData = Class.create();
BoutiqueData.prototype = {
    
    userData: null,
    imgPath: '/data/images/lebensraum/',
    petImg: '/data/images/configurator/pet-active.gif',
    petImgInactive: '/data/images/configurator/pet-inactive.gif',
    infoImg: '/data/images/configurator/icon_info_gold.png',
    
    /**
     * constructor
    **/
    initialize: function (jsonData) {
        this.parseBoutiqueJson(jsonData);
    },
    /**
     * parse received json call
    **/
    parseBoutiqueJson : function (jsonData) {
        var data = jsonData.evalJSON();
        
        //create hash map of json data
        this.userData = new Array();
        //user
        var obj = new Hash();
        obj.set('name', data.user.name); 
        obj.set('icon', data.user.icon);
        if (data.user.subcategories != undefined) {
            obj.set('subcategories', data.user.subcategories);
        } else {
            obj.set('subcategories', '');
        }
        obj.set('additionalinfo', data.user.additionalinfo);
        obj.set('active', true);
        this.userData.push(obj);
        
        //profiles
        if (data.user.profiles != null) {
            for(var i = 0; i < data.user.profiles.length; i++) {
                obj = new Hash();
                obj.set('name', data.user.profiles[i].name);
                obj.set('icon', data.user.profiles[i].icon);
                if (data.user.profiles[i].subcategories != undefined) {
                    obj.set('subcategories', data.user.profiles[i].subcategories);
                } else {
                    obj.set('subcategories', '');
                }
                obj.set('additionalinfo', data.user.profiles[i].additionalinfo);
                obj.set('active', true);
                
                this.userData.push(obj);
            }
        }        

        //window.console.debug(this.userData[0].get('additionalinfo')[0]);
        
        //add eventlistener for submit links
        $('submit_interests').observe('click', this.setHiddenData.bindAsEventListener(this));
        $('submit_adresses').observe('click', this.setHiddenData.bindAsEventListener(this));
        
        //write images for user and profiles
        this.writeAllImgs();
        
        //write tooltips
        this.writeTooltips();
        
    },
    setHiddenData : function (event) {
        var oId = event.findElement().id.slice(7);
        var input = $('form_'+oId).getInputs('hidden');
        
        if(oId == 'interests') {
            input[0].value = Object.toJSON(this.userData);
            
        } else if(oId == 'adresses') {
            var pet = 0;
            var allergic = 0;
            var handicaped = 0;
            for(var i = 0; i < this.userData.length; i++) {
                if(this.userData[i].get('active')) {
                    if (this.userData[i].get('subcategories') != undefined) {
                        for(var j = 0; j < this.userData[i].get('subcategories').length; j++) {
                            input[0].value += this.userData[i].get('subcategories')[j].id + ",";
                        }
                    } else {
                        input[0].value = '';
                    }
                    if(Boolean(this.userData[i].get('additionalinfo').pet)) {
                        pet = 1;
                    }
                    if(Boolean(this.userData[i].get('additionalinfo').allergic)) {
                        allergic = 1;
                    }
                    if(Boolean(this.userData[i].get('additionalinfo').handicaped)) {
                        handicaped = 1;
                    }                
                }
            }
            
            input[1].value = "pet:" + pet + ",allergic:" + allergic + ",handicaped:" + handicaped;
        }
        
        //submit form
        $('form_'+oId).submit();
    },
    /**
     * extract lebensraum name from lebensraum image
    **/
    splitImgName : function (elemSrc) {
        var ln = elemSrc.split('/');
        var numChars = ln[ln.length-1].indexOf('.');
        ln = ln[ln.length-1].slice(0, numChars);
        
        return ln;
    },
    /**
     * compose subcategory image path
     * elements for path: path to images + name lebensraum + subcategory image
     * @param: img, image received from json
    **/
    getComposedImgPath : function (img) {
        var newPath = this.imgPath + this.splitImgName($('lebensraum_img').src) + "/" + img;
        
        return newPath;
    },
    /**
     * check if subcategory image is already writen
     * @param: checkImg, image to check if already available in html
    **/
    checkWrittenImgs : function (checkImg, id) {
        var availImgs = $('lebensraum').childElements();
        var uniqueImg = true;
        
        for(var i = 0; i < availImgs.length; i++) {
           if(availImgs[i].src.indexOf(checkImg) > -1 && availImgs[i].id == id) {
                 uniqueImg = false;
            }
         }
        
        return uniqueImg;
    },
    /**
     * get subcategory image name, first char uppercase
     * @param: image
    **/
    getImgName : function (img) {
        var imgName = img.slice(0, img.indexOf('.'));
        imgName = imgName.substr(0, 1).toUpperCase() + imgName.substr(1);
        
        return imgName;
    },
    /**
     * initial insert of all image tags in html
    **/
    writeAllImgs : function () {
        var hasPet = false;
         $('pagetitle').insert('<ul class="family_icons"></ul>');
        //insert subcategory images for user/profiles
        for(var i = 0; i < this.userData.length; i++) {
            //insert user icon
            $$('.family_icons')[0].insert('<li id="user_' + i + '"><img src="' + this.userData[i].get('icon') + '" alt="' + this.userData[i].get('name') + '" /></li>');
            
            //check if pet
            if(Boolean(this.userData[i].get('additionalinfo').pet)) {
                hasPet = true;
            }
            
            //insert subcategory images for profile
            if (this.userData[i].get('subcategories') != undefined)  { 
                for(var j = 0; j < this.userData[i].get('subcategories').length; j++) {
                    if(this.userData[i].get('subcategories')[j].picture != '') {
                        //compose path
                        var img = this.userData[i].get('subcategories')[j].picture;
                        var imgId = this.userData[i].get('subcategories')[j].id;
                        
                        if (this.checkWrittenImgs(img, imgId)) {
                            $('lebensraum').insert('<img src="' + this.getComposedImgPath(img) + '" alt="" class="gegenstand" id="' + this.userData[i].get('subcategories')[j].id + '" />');
                        }
                    }
                }
            }        
        }
        if(hasPet) {
            $$('.family_icons')[0].insert('<li class="pet"><img src="' + this.petImg + '" alt="Pet" /></li>');
        }
        
        //behaviour
        var userIcons = $$('.family_icons')[0].childElements();
        
        for(i = 0; i < userIcons.length; i++) {
            //click event
            if (userIcons[i].className != "pet") {
                userIcons[i].observe('click', this.iconEventHandler.bindAsEventListener(this));
                userIcons[i].observe('mouseover', this.iconEventHandler.bindAsEventListener(this));
                userIcons[i].observe('mouseout', this.iconEventHandler.bindAsEventListener(this));
            }
        }
        
    },
    /**
     * initial insert of all tooltip constructs
    **/
    writeTooltips : function () {
        var j = 1;
        var dist = 0;
        for(var i = 0; i < this.userData.length; i++) {
            if(Boolean(this.userData[i].get('additionalinfo').pet)) dist = 48
        }
        for(var i = this.userData.length-1; i >= 0; i--) {
            var left = (42 * (j)) + dist;
            var tooltip = '<div id="tooltip_'  + i +'" class="icon_tooltip" style="right: ' + left + 'px;"><img src="' + this.infoImg + '" class="fix" /><div class="icon_tooltip_content">' + this.userData[i].get('name') + '</div></div>';
            
            //insert after #pagetitle
            $('pagetitle').insert({after: tooltip});
            
            j++;
        }
    },
    /**
     * add style attribute to display subcategory images 
     * @param: userObjSubcat, object with subcategories of user/profile
    **/
    showImgs : function (userObjSubcat) {
        for(var i = 0; i < userObjSubcat.length; i++) {
            var id = userObjSubcat[i].id.toString();
            
            //check if subcategory image available
            if(userObjSubcat[i].picture != '') {
                $(id).setStyle({
                    display: 'block'
                });
            }
        }
    },
    /**
     * add style attribute to hide subcategory images 
     * @param: userObjSubcat, object with subcategories of user/profile
    **/
    hideImgs : function (id) {
        $(id).setStyle({
            display: 'none'
        });
    },
    /**
     * event listener user/profile icon clicked
     * @param: userIcons, li od li elements with icons
    **/
    iconEventHandler : function (event) {
        var eventTarget = event.findElement();
        
        if(eventTarget.tagName.toLowerCase() == 'img') {
            eventTarget = eventTarget.up('li');
        }
        
        //get index
        var oId = eventTarget.id.charAt(5);
        
        if(event.type.toLowerCase() == 'click') {
            //replace src
            var oImg = eventTarget.childElements()[0];
            if(oImg.src.indexOf('inactive') == -1) {
                oImg.src = oImg.src.replace(/\-active/g, '-inactive');
                this.userData[oId].set('active', false);
                
                //check if imgs could be hidden
                this.checkToHideSubcatImgs(oId);
                
            } else {
                oImg.src = oImg.src.replace(/\-inactive/g, '-active');
                this.userData[oId].set('active', true);
                if (this.userData[oId].get('subcategories') != undefined)  { 
                    this.showImgs(this.userData[oId].get('subcategories'));
                }            }
            
            //check pet
            this.checkToHidePet(oId);
            
        } else if(event.type.toLowerCase() == 'mouseover') {
            $('tooltip_'+oId).setStyle({
                display: 'block'
            });
            
        } else if(event.type.toLowerCase() == 'mouseout') {
            $('tooltip_'+oId).setStyle({
                display: ''
            });
        }
    },
    /**
     * check if more than one user/profile has subcategory img too
     * if one user is active and has subcategory img too, img visible
     * if no user has subcategory img too or all user which has subcategory img are inactive, img invisible
     * @param: userObj
    **/
    checkToHideSubcatImgs : function (userId) {
        if (this.userData[userId].get('subcategories') != undefined)  { 
            for(var i = 0; i < this.userData[userId].get('subcategories').length; i++) {
                var hideSubcatImg = true;
                
                if(this.userData[userId].get('subcategories')[i].picture != '') {
                    var imgIdToCheck = this.userData[userId].get('subcategories')[i].id;
                
                    for(var j = 0; j < this.userData.length; j++) {
                        if((j != userId) && this.userData[j].get('active')) {  
                            for(var k = 0; k < this.userData[j].get('subcategories').length; k++) {
                                if(this.userData[j].get('subcategories')[k].id.toString() == imgIdToCheck.toString()) {
                                    hideSubcatImg = false;
                                }
                            }
                        }
                    }
                    if(hideSubcatImg) {
                        this.hideImgs(imgIdToCheck.toString());
                    }
                }
            }
        }    
    },
    /**
     * pet img needs to be inactive if no user/profile
    **/
    checkToHidePet : function (actualId) {
        var petToCheck = this.userData[actualId].get('additionalinfo').pet;
        if(petToCheck == 1) {
            var petImgPath = $$('.pet')[0].childElements()[0].src;
            //icon clicked to enable
            if(this.userData[actualId].get('active')) {
                $$('.pet')[0].childElements()[0].src = petImgPath.replace(/\-inactive/g, '-active');
                
              //icon clicked to disable
            } else if(!this.userData[actualId].get('active')) {
                var disablePet = true;
                for(var i = 0; i < this.userData.length; i++) {
                    if(i != actualId)  {
                        if (this.userData[i].get("additionalinfo").pet == 1 && this.userData[i].get('active'))  {
                            disablePet = false;
                        }
                    }
                }
                if (disablePet) {
                    $$('.pet')[0].childElements()[0].src = petImgPath.replace(/\-active/g, '-inactive');
                }            
            }
        }
    }
    
}
/*---------------------------------------------- Overview Interests -------------------------------------------*/
var Interests = Class.create();
Interests.prototype = {
    
    petImg: '/data/images/configurator/pet-active.gif',
    petImgInactive: '/data/images/configurator/pet-inactive.gif',
    checkboxOn: '/data/images/checkbox-on.gif',
    checkboxOff: '/data/images/checkbox-off.gif',
    infoImg: '/data/images/configurator/icon_info_gold.png',
    
 initialize: function () {
        $('pagetitle').insert('<ul class="family_icons_inactive"></ul>');
        this.parseJson();        
    },
    
    parseJson : function () {
        if(typeof json == 'string') {
            this.userData = json.evalJSON();
            this.writeIcons();
            this.activateTabs();
            this.setActiveInterests();
            this.writeTooltips();
               
            //add eventlistener for submit links
            $('submit_same').observe('click', this.setHiddenData.bindAsEventListener(this));
            $('submit_all').observe('click',  this.setHiddenData.bindAsEventListener(this));
        }
    },
    writeIcons : function () {
        var hasPet = false;
        for(var i = 0; i < this.userData.length; i++) {
            //insert user icon
            var imgSrc = this.userData[i].icon;
            
            if(!this.userData[i].active) {
                imgSrc = this.userData[i].icon.replace(/\-active/g, '-inactive');
            }
            $$('.family_icons_inactive')[0].insert('<li id="user_' + i + '"><img src="' + imgSrc + '" alt="' + this.userData[i].name + '" /></li>');
            
            //check if pet
            if(this.userData[i].active && Boolean(this.userData[i].additionalinfo.pet)) {
                hasPet = true;
            }
        }
        if(hasPet) {
            $$('.family_icons_inactive')[0].insert('<li class="pet"><img src="' + this.petImg + '" alt="Pet" /></li>');
        }
        
        //behaviour
        var userIcons = $$('.family_icons_inactive')[0].childElements();
        
        for(i = 0; i < userIcons.length; i++) {
            if (userIcons[i].className != "pet") {
                userIcons[i].observe('click', this.iconEventHandler.bindAsEventListener(this));
                userIcons[i].observe('mouseover', this.iconEventHandler.bindAsEventListener(this));
                userIcons[i].observe('mouseout', this.iconEventHandler.bindAsEventListener(this));
            }
        }    
        
    },
    activateTabs : function () {
        //get tab
        var tabList = $('tabnav').childElements();
        
        for(var i = 0; i < 8; i++) {
            if(this.userData[i]) {
                tabList[i].addClassName('current');
                tabList[i].observe('click', this.tabEventHandler.bindAsEventListener(this));
            }
             else {
               tabList[i].hide();
            }
        }
    },
    setActiveInterests : function () {
        var imgList = $$('.checkbox');
        var ids = this.getAllIds();
        
         for(var j = 0; j < imgList.length; j++) {
            imgList[j].src = imgList[j].src.replace(/\-on/g, '-off');
            imgList[j].next('span').removeClassName('highlight');
        }
        for(var i = 0; i < ids.length; i++) {
            if($('cat_' + ids[i])) {
                $('cat_' + ids[i]).src = $('cat_' + ids[i]).src.replace(/\-off/g, '-on');
            }
        }
        
        var same = this.getSameInterests();
        for(var i = 0; i < same.length; i++) {
            $('cat_' + same[i]).next('span').addClassName('highlight');
        }
    },
    writeTooltips : function () {
        var j = 1;
        var dist = 0;
        
        for(var i = 0; i < this.userData.length; i++) {
            if(Boolean(this.userData[i].additionalinfo.pet)) dist = 48;
        }
        for(var i = this.userData.length-1; i >= 0; i--) {
            var left = (42 * (j)) + dist;
            var tooltip = '<div id="tooltip_'  + i +'" class="icon_tooltip" style="right: ' + left + 'px;"><img src="' + this.infoImg + '" class="fix" /><div class="icon_tooltip_content">' + this.userData[i].name+ '</div></div>';
            $('pagetitle').insert({after: tooltip});            
            j++;
        }
    },
    /**
          * event listener user/profile icon clicked
          * @param: userIcons, li od li elements with icons
          **/
    iconEventHandler : function (event) {
        var eventTarget = event.findElement();
        
        if(eventTarget.tagName.toLowerCase() == 'img') {
            eventTarget = eventTarget.up('li');
        }     
        
        var oId = eventTarget.id.charAt(5);
        
        if(event.type.toLowerCase() == 'click') {
            this.changeTab(oId);   
            this.changeIcon(oId);
            
        } else if(event.type.toLowerCase() == 'mouseover') {
            $('tooltip_'+oId).setStyle({
                display: 'block'
            });
            
        } else if(event.type.toLowerCase() == 'mouseout') {
            $('tooltip_'+oId).setStyle({
                display: ''
            });
        }
    },
    tabEventHandler : function (event) {
        var eventTarget = event.findElement();
        var oId = eventTarget.id.charAt(9);
        
        this.changeTab(oId);   
        this.changeIcon(oId);
    
    },
    changeIcon : function (oId) {
        oImg = $("user_" + oId).down('img');
        if(oImg.src.indexOf('inactive') == -1) {
            oImg.src = oImg.src.replace(/\-active/g, '-inactive');
            this.updateUserData(oId,false);
            
        } else {
            oImg.src = oImg.src.replace(/\-inactive/g, '-active');
            this.updateUserData(oId,true);
        }
    },
    changeTab : function (oId) {
    
        var oTab = $("tab_user_" + oId);
        if(oTab.tagName.toLowerCase() == 'span') {
            oTab = oTab.up('li');
        }    
        if (oTab.hasClassName('current')){
            oTab.removeClassName('current');  
            this.updateUserData(oId,false);
        }
        else {        
            oTab.addClassName('current');  
            this.updateUserData(oId,true);            
        }   
    },
    updateUserData : function (oId, bActivate) {
        this.userData[oId].active = bActivate;
        this.checkToHidePet(oId);
        this.setActiveInterests();
    },
    getSameInterests :function () {
        var ids = this.getAllIds();
        var helper = ids.clone();
        var sameIds = new Array();
        
        for(var i = 0; i < ids.length; i++) {
            var searchId = ids[i];
            var counter = 0;
            for(var j = 0; j < helper.length; j++) {
                if(searchId == helper[j]) {
                    counter++;
                    helper[j] = null;
                }
            }
            if(counter > 1) {
                sameIds.push(searchId);
            }
        }
        return sameIds;
    },    
    checkToHidePet : function (actualId) {
        var petToCheck = this.userData[actualId].additionalinfo.pet;
        if(petToCheck == 1) {
            var petImgPath = $$('.pet')[0].childElements()[0].src;
            //icon clicked to enable
            if(this.userData[actualId].active) {
                $$('.pet')[0].childElements()[0].src = petImgPath.replace(/\-inactive/g, '-active');
                
              //icon clicked to disable
            } else if(!this.userData[actualId].active) {
                var disablePet = true;
                for(var i = 0; i < this.userData.length; i++) {
                    if(i != actualId)  {
                        if (this.userData[i].additionalinfo.pet == 1 && this.userData[i].active)  {
                            disablePet = false;
                        }
                    }
                }
                if (disablePet) {
                    $$('.pet')[0].childElements()[0].src = petImgPath.replace(/\-active/g, '-inactive');
                }            
            }
        }
    },    
    setHiddenData : function (event) {
        var oId = event.findElement().id.slice(7);
        var input = $('interests').getInputs('hidden');
        input[0].value = "";
        input[1].value = "";
        
        var pet = 0;
        var allergic = 0;
        var handicaped = 0;
        var sameInterests = this.getSameInterests();
        
        if(oId == 'same') {
            for(var i = 0; i < sameInterests.length; i++) {
                input[0].value += sameInterests[i] + ",";
            }
        }
        for(var i = 0; i < this.userData.length; i++) {
            if(this.userData[i].active) {
                if (this.userData[i].subcategories != undefined) {
                    for(var j = 0; j < this.userData[i].subcategories.length; j++) {
                        if(oId == 'all' || (oId == 'same' && sameInterests.length == 0)) {
                        
                            if(input[0].value.indexOf(this.userData[i].subcategories[j].id) == -1) {
                                input[0].value += this.userData[i].subcategories[j].id + ",";
                            }
                        }
                    }
                } else {
                    input[0].value = '';
                }
                if(Boolean(this.userData[i].additionalinfo.pet)) {
                    pet = 1;
                }
                if(Boolean(this.userData[i].additionalinfo.allergic)) {
                    allergic = 1;
                }
                if(Boolean(this.userData[i].additionalinfo.handicaped)) {
                    handicaped = 1;
                }            
            }
        }
        
        input[1].value = "pet:" + pet + ",allergic:" + allergic + ",handicaped:" + handicaped;
        //alert(input[0].value + "/" + input[1].value);
        $('interests').submit();
    },
    getAllIds : function () {
        var allIds = new Array();
        for(var i = 0; i < this.userData.length; i++) {
            if(this.userData[i].active) {
                if (this.userData[i].subcategories != undefined) {
                    for(var j = 0; j < this.userData[i].subcategories.length; j++) {
                        allIds.push(this.userData[i].subcategories[j].id);
                    }
                }            
            }
        }
        return allIds;
    }
}
/*---------------------------------------------- TabNavigation -------------------------------------------*/

var TabManager = Class.create();
TabManager.prototype = {
    initialize: function () {
        this.activateTabs();  
        
    },
    activateTabs : function () {
        var tabList = $('tabnav').childElements();
        for(var i = 0; i < 8; i++) {
                tabList[i].observe('click', this.tabEventHandler.bindAsEventListener(this));
        }
    },
    tabEventHandler : function (event) {
        var oId = event.findElement().id.slice(12);
        if ($('currentProfile') && oId != $('currentProfile').value) {
            var sName = $('profiles').className;
            if(sName == 'saveform') {            
                if($('profilecount').value > 0 || $('loggedin').value == "yes") {                
                    if(oId > $('profilecount').value) {
                        oId = parseInt($('profilecount').value) + 1;
                    }
                    profile_shownext(oId);
                }
            }
            
            if(sName == 'interests') {   
                if(oId > $('profilecount').value) {
                    document.interessen_speichern.type.value='new';
                    $('currentProfile').value = parseInt($('profilecount').value) + 1;
                    document.interessen_speichern.submit();
                }
                else {
                    document.interessen_speichern.type.value='new';
                    profile_shownext(oId);
                }
            }
            
            if(sName == 'profiles') {     
                
                if(oId > $('profilecount').value) {
                         profile_check();   
                        
                }
                else {
                    if (oId <= $('profilecount').value) {
                        profile_show(oId);
                    }
                }              
            }
        }
    }
} 
/*---------------------------------------------- Adresses -------------------------------------------*/
var Adresses = Class.create();
Adresses.prototype = {
    initialize: function () {
        var openLinks = $('adress_db').getElementsBySelector('a.showmatching');
        for (var i=0; i < openLinks.length; i++) {
            openLinks[i].observe('click', this.showMatchings.bindAsEventListener(this));
        }
        var closeLinks = $('adress_db').getElementsBySelector('a.close');
        for (var j=0; j < closeLinks.length; j++) {
            closeLinks[j].observe('click', this.hideMatchings.bindAsEventListener(this));
        }
    },
    showMatchings: function(event) {
        var eventTarget = event.findElement();
        var resortTeaser = eventTarget.up('.showmatching');
        var matchingTeaser = $(resortTeaser.id.replace('resort', 'resortmatching')); 
        if (resortTeaser != undefined) {
            resortTeaser.addClassName('hiddenteaser');
        }
        if (matchingTeaser != undefined) {
            matchingTeaser.removeClassName('hiddenteaser');
        }
    },
    
    hideMatchings: function(event) {
        var eventTarget = event.findElement();
        var matchingTeaser = eventTarget.up('.hidematching');
        var resortTeaser = $(matchingTeaser.id.replace('resortmatching', 'resort')); 
        if (resortTeaser != undefined) {
            resortTeaser.removeClassName('hiddenteaser');
        }
        if (matchingTeaser != undefined) {
            matchingTeaser.addClassName('hiddenteaser');
        }
    }
}
