﻿

/*################################################# Image Maps ############################################*/
/*#########################################################################################################*/
function initImageMap(map) {
    
    // Check if map exists
    if(map) {
    
        //check if dbteaser exist
        if($('dbteaser')) {
            var infoDivs = $('dbteaser').childElements();
              for(var i = 0; i < infoDivs.length; i++) {
               if (infoDivs[i].tagName == "DIV"){
                showHideHoverMap(infoDivs[i].id, false);
               }
            }
            
            if($('teaser_default')) {
                $('teaser_default').style.display = 'block';
            }
        }
        
        // Get all the areas of the imagemap
        var country_list = map.getElementsByTagName('AREA');
        
        // Get all the items of the country nav
        var country_nav = $('country_nav').getElementsByTagName('LI');
        //hold last shown teaser
        var lastId = "teaser_default";
        
        // Loop through all areas
        for(var i=0; i<country_list.length; i++){
            country_list[i].style.display = 'none';
            
            // Assignin an action to the mouseover event
            Event.observe(country_list[i], 'mouseover', function(e) {
                // Get the id from the hovered area
                var id = this.id;
                
                // Extract the "country"-part of the id = the id of the list-item
                var country_id = "detail" + id.substring(id.indexOf('_'), id.length);
               
                //show map hover
                showHideHoverMap(country_id, true);
                
                //if there's a description teaser -> show it
                showTeaser(id);
            });
            
            // Assign an action to the mouseout event
            Event.observe(country_list[i], 'mouseout', function(e) {
                // Get the id from the hovered area
                var id = this.id;
                
                // Extracti the "country"-part of the id = the id of the list-item
                var country_id = "detail" + id.substring(id.indexOf('_'), id.length);
                
                //show map hover
                showHideHoverMap(country_id, false);
                
                //if there's a description teaser -> hide it
                hideTeaser(id);
            });
                        
        }
        
        // Loop through all country nav items
        for(var i=0; i<country_nav.length; i++){
            
            // Assignin an action to the mouseover event
            Event.observe(country_nav[i], 'mouseover', function(e) {
                // Get the id from the hovered area
                var id = this.id;
                
                // Extract the "country"-part of the id = the id of the list-item
                country_id = "detail_" + id;
                
                //show map hover
                showHideHoverMap(country_id, true);
                
                //if there's a description teaser -> show it
                var teaser_id = "teaser_" + id;
                showTeaser(teaser_id);
            });
            
            // Assign an action to the mouseout event
            Event.observe(country_nav[i], 'mouseout', function(e) {
                // Get the id from the hovered area
                var id = this.id;
                // Extracti the "country"-part of the id = the id of the list-item
                country_id = "detail_" + id;
                
                //show map hover
                showHideHoverMap(country_id, false);
                
                //if there's a description teaser -> hide it
                var teaser_id = "teaser_" + id;
                hideTeaser(teaser_id);
                
            });
            
         }
    }
}
function showHideHoverMap(id, visibility) {
  if($(id)) {
    if(visibility) {
        $(id).setStyle({
            display: 'block'
        });
    } else {
        $(id).setStyle({
            display: 'none'
        });
    }
  } 
}
function showTeaser(id) {
    //if there's a description teaser -> hide it
    if($('dbteaser')) {
        // hide default teaser
        if($('teaser_default')) {
            if($('teaser_default').getStyle('display') == 'block') {
                $('teaser_default').style.display = 'none';
            }
        }
        var teaser = $('dbteaser').childElements();
        for(var i = 0; i < teaser.length; i++) {
           if(teaser[i].tagName == "DIV"){
                showHideHoverMap(teaser[i].id, false);
            }
        }         
             
        var teaser_id = "teaser" + id.substring(id.indexOf('_'), id.length);
        showHideHoverMap(teaser_id, true);
    }
}
function hideTeaser(id) {
    //if there's a description teaser -> show it
    if($('dbteaser')) {
        if($('teaser_default')) {
            if($('teaser_default').getStyle('display') == 'none') {
                $('teaser_default').style.display = 'block';
            }
        }
       
        var teaser_id = "teaser" + id.substring(id.indexOf('_'), id.length);
        if($(teaser_id )) {            
            showHideHoverMap(teaser_id, false);
        }
    }
}
/*################################################### Footer ##############################################*/
/*#########################################################################################################*/
function centerFooter() {
    if($('maincontent_footer')) {
    var baseFontSize = parseInt($(document.body).getStyle('font-size'));    
    var footerItems = $('maincontent_footer').childElements('li');
    var footerWidth = $('maincontent_footer').getDimensions().width;
    
        if(footerItems.length > 1) {
        footerItems[footerItems.length-1].setStyle({
            cssFloat: 'right'
        });
            
        if(footerItems.length == 3) {
        var margin = footerWidth;
        for(var i = 0; i < footerItems.length; i++) {
            margin -= footerItems[i].getDimensions().width;
        }
        margin = margin / 2;
        margin = margin / baseFontSize + "em";
                
        footerItems[0].setStyle({
            marginRight: margin
        });
        }
    }
    }
}
/*################################################## Accordion ############################################*/
/*#########################################################################################################*/
function loadAccordion() {
        
    var mainAccordion = new accordion('accordion_list');
    
    // Open first one
    mainAccordion.activate($$('#accordion_list .accordion_toggle')[0]);
    
}

/*######################################### Familienverhältnisse ##########################################*/
/*#########################################################################################################*/
function setFamilyIcons() {
    
    // get emtpty elems
    var emptyElems = $('familie_felder').down('ul').childElements();
    var emptyImg = emptyElems[0].down('img').src;
    
    var helper = 0;
    
    var familyElems = $('familie_auswahl').down('ul').childElements();
    
    // get family images
    var familyImgs = new Array;
    
    // familyElems.length-1 because last li is checkbox
    for(var i = 0; i < familyElems.length-1; i++) {
        
        var name = familyElems[i].down('img').getAttribute('name');
        familyImgs[name] = (familyElems[i].down('img').getAttribute('src'));
        
        emptyElems[i].taken = false;
        
        // add event handler
        Event.observe(familyElems[i], 'click', function() {
            
            for(var j = 0; j < emptyElems.length; j++) {
                
                if(!emptyElems[j].taken) {
                    
                    emptyElems[j].down('img').src = familyImgs[this.down('img').getAttribute('name')];
                    emptyElems[j].taken = true;
                    
                    // activate click for taken field
                    emptyElems[j].addClassName('cursor');
                    Event.observe(emptyElems[j], 'click', function() {
                        this.down('img').src = emptyImg;
                        this.taken = false;
                        this.removeClassName('cursor');
                    });
                    break;
                }
            }
        });
    }
}

/*############################################### Boutique ################################################*/
/*#########################################################################################################*/
var Rules = { 
      rules: "1.0",
   
   '#no_member:focus' : function(element, event) {
        initializeMyHapimagForm(1);
        Event.stop(event);
    },
    
    '#member:focus' : function(element, event) {
        initializeMyHapimagForm(0);
        Event.stop(event);
    },
    
    '#member_login:focus' : function(element, event) {
        initializeMyHapimagForm(2);    
        Event.stop(event);
    },    

   '#submituserdata:click' : function(element, event) {
        var username = $F('userno2');
        var pwd = $F('pw2');
        
        if(username && pwd) {
        
            var oAjax = new Ajax.Request(
               '/de/myhapimag-getssodata.htm',
               {
                   method: 'post',
                    parameters: "?userid=" + username + "&password=" + pwd,
                    onSuccess: function(transport) {
                        parseUserJson(transport.responseText);
                    },
                    onFailure: function(transport) {
                        $('state2_0').setStyle({
                            display: 'none'
                        });
                        $('state2_1').setStyle({
                            display: 'none'
                        });
                        $('state2_2').setStyle({
                            display: 'none'
                        });
                        $('state2_3').setStyle({
                            display: 'block'
                        });                    
                    }
               }
            );
        } else {
            $('state2_0').setStyle({
                display: 'block'
            });
            $('state2_1').setStyle({
                display: 'none'
            });
            $('state2_2').setStyle({
                display: 'none'
            });
            $('state2_3').setStyle({
                display: 'none'
            });
        }
        
        Event.stop(event);
    }
    
}

function initializeMyHapimagForm(state) {
    if (state == 2) {
        $('state0').setStyle({
            display: 'none'
        });
        $('state2').setStyle({
            display: 'block'
        });
        $('state2_0').setStyle({
            display: 'none'
        });
        $('state2_2').setStyle({
            display: 'none'
        });
        $('state2_3').setStyle({
            display: 'none'
        });
        if ($('firstname2') && $('firstname2').value != '') {
            $('state2_1').setStyle({
                display: 'block'
            });
            $('f2').disabled = true;
            $('m2').disabled = true;
        } else {
            $('state2_1').setStyle({
                display: 'none'
            });
        }
    } 
    else if (state == 0) {
        $('state2').setStyle({
            display: 'none'
        });
        $('state0').setStyle({
            display: 'block'
        });
        $$('.state0')[0].setStyle({
            display: 'none'
        });
        $('state1').removeClassName('invisible');
        $$('.state1')[0].setStyle({
            display: 'block'
        });
    }
    else {
        //element.
        $('state1').addClassName('invisible');
        $$('.state1')[0].setStyle({
            display: 'none'
        });
        $('state2').setStyle({
            display: 'none'
        });
        $('state0').setStyle({
            display: 'block'
        });
        $$('.state0')[0].setStyle({
            display: 'block'
        });
    }
}

function parseUserJson(json) { 
    var data = json.evalJSON();
    
    if (data[0] == 0) {
        if(data[1] == 'f') {
            $('f2').checked = true;
            $('sex2').value = 2;
        } else if(data[1] == 'm') {
            $('m2').checked = true;
            $('sex2').value = 1;
        }
        $('f2').disabled = true;
        $('m2').disabled = true;
        $('firstname2').value = data[2];
        $('lastname2').value = data[3];
        $('email2').value = data[4];
        $('geb2').value = data[5];
        $('street_no2').value = data[6];
        $('plz2').value = data[7];
        $('city2').value = data[8];
        
        
        $('state2_0').setStyle({
            display: 'none'
        });
        $('state2_1').setStyle({
            display: 'block'
        });
    } else if (data[0] == 1) {
        $('state2_0').setStyle({
            display: 'none'
        });
        $('state2_1').setStyle({
            display: 'none'
        });
        $('state2_2').setStyle({
            display: 'block'
        });
        $('state2_3').setStyle({
            display: 'none'
        });
        
    } else {
        $('state2_0').setStyle({
            display: 'none'
        });
        $('state2_1').setStyle({
            display: 'none'
        });
        $('state2_2').setStyle({
            display: 'none'
        });
        $('state2_3').setStyle({
            display: 'block'
        });
    }
}
/*################################################ Carousel ###############################################*/
/*#########################################################################################################*/
function runTest() {
    vCarousel = new UI.Carousel("vertical_carousel", {direction: "vertical", scrollInc: 1});
}

/*################################################ init ###################################################*/
/*#########################################################################################################*/
document.observe("dom:loaded", function() {
    
    centerFooter();
    setExternalLinkIcon();

    if ($('state0')) {
        //start rules for Ajax call
        EventSelectors.start(Rules);
            
    }
    main();
    
    // init carousel
    if ($('vertical_carousel')) {
        runTest();
    } 

    //init accordion
    $('basic-accordian') ? new Accordian('basic-accordian',5,'header_active') : null;
    $('basic-accordian-teaser') ? new Accordian('basic-accordian-teaser',5,'header_active') : null;
    $('basic-accordian-subnav') ? new Accordian('basic-accordian-subnav',5,'header_active') : null;

    //init boutique via ajax call
    if ($('lebensraum')) {
        var oAjax = new Ajax.Request(
           '/de/myhapimag-json.htm',
           {
               method: 'post',
                onSuccess: function(transport) {
                    var bd = new BoutiqueData(transport.responseText);
                },
                onFailure: function(transport) {
                    $('errorMsg').update('<span class="warning">Fehler beim laden der Daten. Bitte versuchen sie es sp&#228;ter erneut.</span>');
                    $('errorMsg').setStyle({
                        display: 'block'
                    });
                }
           }
        );
    } 

    if ($('interests')) {
        var interests = new Interests();
    } 
    if ($('profiles')) {
        var tabs = new TabManager();
    }
    if ($('adress_db')) {
        var adresses = new Adresses();
    }    
    if($$('ul.info_list') > 0) {
        $$('ul.info_list').each(function(ul, i) {
            floatList(ul);
        });
    }


  //tandem tours de-/activate select
    if($('tandem_tours')) {
        if($F('land') == "") {
            $('adress').disable();
        }
        
        //click handler
        $('land').observe('change', function(event) {
            if($F('land') == "") {
                $('adress').disable();
            } else {
                $('adress').enable();
            }
        });
    }
    
    //tandem tours tabs
    if($('tabnav')) {
        if($('tabnav').hasClassName('tandem')) {
            switchTab();
        }
    }
    
    //tandem tours form participants
    if($('booking_request')) {
        var participantList = $('participant_section').childElements('li');
        var numParticipants = participantList.length - 1;
        var numVisible = 1;
        
        //first clear form fields
        clearFormFields(1);
        //if checkbox checked disable participant 1 form fields
        if($('participant').checked) {
            toggleParticipantOne(false, 1);
        }
        
        //form fields handler to fill in field values in participant 1 form fields if checkbox checked
        $('m').observe('click', function() {
            if($('participant').checked) {
                if($('m').checked) {
                    $('m_part1').checked = true;
                } else {
                    $('f_part1').checked = true;
                }
            }
        });
        $('f').observe('click', function() {
            if($('participant').checked) {
                if($('m').checked) {
                    $('m_part1').checked = true;
                } else {
                    $('f_part1').checked = true;
                }
            }
        });
        $('surname').observe('blur', function() {
            if($('participant').checked) {
                $('surname_part1').value = $('surname').value;
            }
        });
        $('name').observe('blur', function() {
            if($('participant').checked) {
                $('name_part1').value = $('name').value;
            }
        });
        $('datebirth').observe('blur', function() {
            if($('participant').checked) {
                $('datebirth_part1').value = $('datebirth').value;
            }
        });
        
        //click handler for checkbox
        $('participant').observe('click', function() {
            if(this.checked) {
                //nur ein Teilnehmer vorhanden
                if(numVisible == 1) {
                    //disable form fields
                    toggleParticipantOne(false, 1);
                    //fill in values
                    if($('participant').checked) {
                        //daten von oberem formular in teilnehmer formular
                        fillFormFields(1);
                    }
                    
                    //mehrere Teilnehmer bereits ausgefüllt
                } else if(numVisible > 1) {
                    //fülle felder von nächsmöglichem element aus und schiebe es an platz 1
                    //fill in values
                    if($('participant').checked) {
                        //daten von oberem formular in teilnehmer formular
                        participantList[numVisible].show();
                        fillFormFields(numVisible + 1);
                        numVisible++;
                    }
                }
                
            } else {
                if(numVisible == 1) {
                    toggleParticipantOne(true, 1);
                    //clear form
                    clearFormFields(1);
                    
                } else {
                    numVisible--;
                    participantList[numVisible].hide();
                    clearFormFields(numVisible + 1);
                }
            }
        });
        
        //hide all except first & last
        for(var i = 1; i < numParticipants; i++) {
            participantList[i].hide();
        }
        
        $('add_more').observe('click', function(e) {
            //don't trigger click
            Event.stop(e);
            
            //show next
            if(numVisible < numParticipants) {
                participantList[numVisible].show();
                numVisible++;
            }
        });
    }

});


function toggleParticipantOne(enable, num) {
    if(enable) {
        $('m_part' + num).enable();
        $('f_part' + num).enable();
        $('surname_part' + num).enable();
        $('name_part' + num).enable();
        $('datebirth_part' + num).enable();
        datePickerController.enable('datebirth_part' + num);
    
    } else {
        $('m_part' + num).disable();
        $('f_part' + num).disable();
        $('surname_part' + num).disable();
        $('name_part' + num).disable();
        $('datebirth_part' + num).disable();
        datePickerController.disable('datebirth_part' + num);
    }
}
function clearFormFields(num){
    $('m_part' + num).checked = false;
    $('f_part' + num).checked = false;
    $('surname_part' + num).value = "";
    $('name_part' + num).value = "";
    $('datebirth_part' + num).value = "";
}
function fillFormFields(num) {
    if($('m').checked) {
        $('m_part' + num).checked = true;
    } else {
        $('f_part' + num).checked = true;
    }
    $('surname_part' + num).value = $('surname').value;
    $('name_part' + num).value = $('name').value;
    $('datebirth_part' + num).value = $('datebirth').value;
}
//floats lists automatically
function floatList(pUl) {
    pUl.childElements().each(function(paLi) {
        paLi.childElements().each(function(elem) {
            if(elem.inspect() == '<ul>') {
                var rightPos = new Array();
                var leftPos = new Array();
                
                var rightLi = new Array();
                var leftLi = new Array();    
                elem.childElements().each(function(targetLi, i) {
                    var offsetPos = targetLi.positionedOffset();
                    if(i % 2 != 0) {
                        rightLi.push(targetLi);
                        targetLi.addClassName('float_right');
                        rightPos.push(offsetPos[0]);
                        
                    } else {
                        leftLi.push(targetLi);
                        leftPos.push(offsetPos[0]);
                    }
                });
                for(var i = 1; i < rightPos.length; i++) {
                    if(rightPos[i-1] != rightPos[i]) {
                        rightLi[i].removeClassName('float_right');
                    }
                }
                for(var i = 1; i < leftPos.length; i++) {
                    if(leftPos[i-1] != leftPos[i]) {
                        leftLi[i].addClassName('float_right');
                    }
                }
            }
        });
        
    });
}
function setExternalLinkIcon() {
    //get all links
    var a = $$('a');
    
    for(var i = 0; i < a.length; i++) {
        var href = a[i].readAttribute('href');
        
        if(href != null) {
            var hrefBegin = href.substring(0, 4);

            if(hrefBegin.include('http') && !href.include('http://www.hapimag.')) {
                if(a[i].down('img') == undefined) {
                    a[i].addClassName('external');
                }
            }
        }
    }
}

/*################################################ Maxlength ##############################################*/
/*#########################################################################################################*/
function imposeMaxLength(Object, MaxLen)
{
  return (Object.value.length <= MaxLen);
}

/*################################################ Highlight ##############################################*/
/*#########################################################################################################*/
function replaceMe(str, phrase, chg) {
    var pattern = new RegExp (phrase ,'ig');
    return str.replace( pattern, chg);
}

function markText(txtKeyword, inputHtml) {
       var re;                               
       var varMatches;                          
       var outHtml;                          
       var replaceText;
       replaceText = '<span style="color:red;">'+txtKeyword+ '</span>';
       re=new RegExp("(\<[^>][^<]*\>)([^<]*)","g");   

       outHtml=new String('');               
       while ((varMatches = re.exec(inputHtml)) != null) {
         outHtml+=varMatches[1];     
         outHtml+=replaceMe(varMatches[2], txtKeyword, replaceText); 
       }
       return outHtml;
}

function main(){
    var ref = document.location.href;
    var hiliteUrl = new String('hilite');
    var arr;
    var hiliteText;
    
    arr = ref.split('&');
    for (var i=0 ; i < arr.length; i++) {
        var idx = arr[i].indexOf(hiliteUrl + '=');    
        if (idx != -1){
            hiliteText =  unescape(arr[i].substring(idx+hiliteUrl.length+1));
                hiliteText = replaceMe(hiliteText, '\\+', ' ');
        
            if (hiliteText.length != 0) {
                var inHtml;
                var outHtml;

                inHtml = $('main_content').innerHTML;        
                outHtml = markText(hiliteText, inHtml);
                $('main_content').innerHTML = outHtml;
            }
            return;
        }
    }
}

function onLoad(){
  main();
  return;
}

/*################################################ Cookies ################################################*/
/*#########################################################################################################*/

function setCookie(name, value, expire, path, domain, secure) {
    
    if (expire) {
        var dtExpire = new Date();
        dtExpire  = new Date(dtExpire.getTime()+1000*60*60*24*expire);
    }
    var sCookie = escape(name)+'='+escape(value) +
    ((expire) ? ";expires=" + dtExpire  .toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";secure" : "");
    
    document.cookie = sCookie;
}

/*################################################ Konfigurator ###########################################*/
/*#########################################################################################################*/

function setType(type, image) {
    $('type').value = type;
    $('typeImage').value = image;
    document.types.submit();
} 

function profile_interests() {
    //if($('currentProfile').value == $('profilecount').value) $('profileSubmitted').value = "false";
    $('task').value = "save_info";
    $('showError').value = "false";
    $('profiles').submit();
}

function interests_submit() {
    $('type').value='new';
    $('currentProfile').value = 1;
    $('profiles').submit();
}
 
function profile_back(back,url) {
    if(back == 1)
    {
        $('currentProfile').value = parseInt($('currentProfile').value) - 1;
        $('profileSubmitted').value = "false";
        if( $('currentProfile').value > 0)
        {
            $('show').value = "info";
            $('profiles').submit();
        }
        else
        {
            document.location.href = url; 
        }
    }
    else if(back == 2)
    {
        $('profileSubmitted').value = "false";
        $('show').value = "info";
        $('profiles').submit();
    }
}

function profile_new() {
    $('task').value = "new";
    $('showError').value = "true";
    $('profiles').submit();
}

function profile_show(iProfileNo) {
    $('profileSubmitted').value = "true"; 
    $('showError').value = "true";
    $('newProfile').value = iProfileNo;    
    if(parseInt(iProfileNo) == 0) {
        $('task').value = "showfirst";
    }
    else {
        $('task').value = "showprofiles";    
    }
    $('profiles').submit();
}

function profile_shownext(iProfileNo) {
    $('currentProfile').value = iProfileNo;
    $('show').value = 'info';
    $('task').value = "showprofiles";    
    $('profiles').submit();
}

function profile_check() {
    $('showError').value = "true";
    $('task').value = "check";
    $('profiles').submit();
}

function profile_save() {
    $('task').value = "save";
    $('profiles').submit();
}

function profile_update() {
    $('task').value = "update";
    $('profiles').submit();
}

function transformUserJson(json) {
    var data = eval(json);
    //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);
    obj.set('subcategories', data.user.subcategories);
    obj.set('additionalinfo', data.user.additionalinfo);
    obj.set('active', true);
    this.userData.push(obj);
    
    //profiles
    if (data.user.profiles != undefined) {
        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);
            obj.set('subcategories', data.user.profiles[i].subcategories);
            obj.set('additionalinfo', data.user.profiles[i].additionalinfo);
            obj.set('active', true);
            
            this.userData.push(obj);
        }    
    }
    return Object.toJSON(this.userData);
}

function checkWantInformations(oForm) {
    if (oForm && oForm.more_infos && oForm.login_radio) {
        moreInfos = oForm.more_infos.checked;
        for(i = 0; i < oForm.login_radio.length; i++) {
            if (oForm.login_radio[i].checked) {
                loginState = oForm.login_radio[i].value;
            }
        }
        if (moreInfos && loginState == "state1") {
            pageTracker._trackPageview('/de/myhapimag/neukunden-info');
        }
    }
    
    oForm.submit();
}

function setEventValues(form,datum,event,ort,code) {
    $(form.id).eventdatum.value = datum;
    $(form.id).eventtext.value = event.replace(/\"/gi, '\'');
    $(form.id).eventort.value = ort.replace(/\"/gi, '\'');
    $(form.id).eventcode.value = code.replace(/\"/gi, '\'');
}