﻿var Carrousel = new Class({
    initialize: function()
    {
        // config
        this.oldURL                    = window.location.href;
        
        this.baseURL                = window.location.href;
        this.baseURL                = this.baseURL.replace(/^(http.*\/)[^/]*$/i, '$1');
        
        this.dataUrl                 = this.baseURL + '../caroussel/products.txt';
        this.imgPath                 = this.baseURL + '../caroussel/img/';
        
        this.maxItems                = 15;
        this.sizes                    = [' kleiner ',' mittelgroßer ',' großer '];
        
        // member var
        this.data                     = this.getDataFromXml();
        this.ItemCount                = 0;
        this.ItemCountFiltered        = 0;
        this.pageNum                = 0;
        this.currentPage            = 0;
        this.qs_dogphase            = 0;
        this.slider                    = null;
        this.history                = null;
            
        
    },
        
    init: function()
    {
        this.checkParams();
        // add functionality to the slider-element
        this.initSlider();
        
        // parse variables from querystring
        this.setQsVariables();
        this.parseAnchorURL();
        // filter checkboxen
        $('filter_nass').addEvent('click', function(event){ $('filter_nass').clicked=false;this.update();this.buildAnchorURL();}.bind(this));
        $('filter_nass').addEvent('mousedown', function(event){ $('filter_nass').clicked=true;this.showLoading(); }.bind(this));
        $('filter_nass').addEvent('mouseleave', function(event){ if ($('filter_nass').clicked!=null && $('filter_nass').clicked==true) {this.update();this.buildAnchorURL();} }.bind(this));
        $('filter_trocken').addEvent('click', function(event){ $('filter_trocken').clicked=false;this.update();this.buildAnchorURL(); }.bind(this));
        $('filter_trocken').addEvent('mousedown', function(event){ $('filter_trocken').clicked=true;this.showLoading(); }.bind(this));
        $('filter_trocken').addEvent('mouseleave', function(event){ if ($('filter_trocken').clicked!=null && $('filter_trocken').clicked==true) {this.update();this.buildAnchorURL();}}.bind(this));
        $('filter_snack').addEvent('click', function(event){ $('filter_snack').clicked=false;this.update();this.buildAnchorURL(); }.bind(this));
        $('filter_snack').addEvent('mousedown', function(event){ $('filter_snack').clicked=true;this.showLoading(); }.bind(this));
        $('filter_snack').addEvent('mouseleave', function(event){ if ($('filter_snack').clicked!=null && $('filter_snack').clicked==true) {this.update();this.buildAnchorURL();} }.bind(this));
        $('filter_func_snack').addEvent('click', function(event){ $('filter_func_snack').clicked=false;this.update();this.buildAnchorURL(); }.bind(this));
        $('filter_func_snack').addEvent('mousedown', function(event){ $('filter_func_snack').clicked=true;this.showLoading(); }.bind(this));
        $('filter_func_snack').addEvent('mouseleave', function(event){ if ($('filter_func_snack').clicked!=null && $('filter_func_snack').clicked==true) {this.update();this.buildAnchorURL();} }.bind(this));
        
        // button
        $('los').addEvent('click', function(event){ $('los').clicked=false;this.update();this.buildAnchorURL();this.checkParams(); }.bind(this));
        $('los').addEvent('mousedown', function(event){ $('los').clicked=true;this.showLoading(); }.bind(this));
        $('los').addEvent('mouseout', function(event){ if ($('los').clicked!=null && $('los').clicked==true) {this.update();this.buildAnchorURL();} }.bind(this));
        
        // inputs
        $('month').addEvent('keyup', function(event){ this.displayDogPhase(); /*this.buildAnchorURL();*/ }.bind(this));
        $('years').addEvent('keyup', function(event){ this.displayDogPhase();/*this.buildAnchorURL();*/ }.bind(this));
        //$('dogname').addEvent('keyup', function(event){ this.buildAnchorURL(); }.bind(this));
        
        // load the initial set of products
        this.update();
        
        this.urlChangeMonitor.periodical(50, this);
        
        $('years').setProperty('maxlength', 2);
        $('month').setProperty('maxlength', 2);
        
    },
    urlChangeMonitor: function ()
    {
        if (this.oldURL!=window.location.href) {
            this.parseAnchorURL();
            this.update();
            //this.buildAnchorURL();
            this.oldURL=window.location.href;
        }
    },
    
    strToBool: function(val)
    {
        return (val=='true'?true:false);
    },
    
    buildAnchorURL: function()
    {
        var size = $('result_rasse_input').value;
        var years = $('years').value;
        var month = $('month').value;
        var baseURL = window.location.href;
        baseURL = baseURL.replace(/(#.*)$/i, '');
        //alert(baseURL);
        var nass = $('filter_nass').checked;
        var trocken = $('filter_trocken').checked;
        var snack = $('filter_snack').checked;
        var func_snack = $('filter_func_snack').checked;
        var name = encodeURIComponent($('dogname').value);
        window.location.href=baseURL+'#'+'size:'+size+';years:'+years+';month:'+month+';nass:'+nass+';trocken:'+trocken+';snack:'+snack+';func_snack:'+func_snack+';name:'+name+';page:'+this.currentPage;
        this.oldURL = window.location.href;
    },
    
    parseAnchorURL: function()
    {
        //alert('parseurl');
        var url = window.location.href;
        var anchor = url.replace(/^http.*#(.*)$/i, '$1');
        
        if (anchor.test(/^http/g)) return false;
        
        var tupel_a = anchor.split(';');
        tupel_a.each(function(tupel) {        
            if ($type(tupel)=='string')
            {
                var kv = tupel.split(':');
                if (kv.length==2)
                {
                    var key = kv[0];
                    var val = kv[1];
                    switch (key)
                    {
                        case 'nass':
                            $('filter_nass').checked=this.strToBool(val);
                        break;
                        case 'trocken':
                            $('filter_trocken').checked=this.strToBool(val);
                        break;
                        case 'snack':
                            $('filter_snack').checked=this.strToBool(val);
                        break;
                        case 'func_snack':
                            $('filter_func_snack').checked=this.strToBool(val);
                        break;
                        case 'page':
                            this.currentPage=parseInt(val);
                        break;
                        case 'month':
                            if (val!='') $('month').value=parseInt(val);
                        break;
                        case 'years':
                            if (val!='') $('years').value=parseInt(val);
                        break;
                        case 'size':
                            if (val=='') break;
                            var temp = parseInt(val);
                            this.slider.set(temp+1);
                            temp = Math.max(temp,-1);
                            temp = Math.min(temp,2);
                            $('result_rasse_input').value = temp;
                        break;
                        case 'name':
                            $('dogname').value=decodeURIComponent(val);
                        break;
                    }
                }
            }
        }.bind(this));
        
/*        if (url.match(/[\?\&]product=(nass|trocken|snack)/i)) {
            var check=url.replace(/^.*[\?\&]product=(nass|trocken|snack).*$/i, '$1');
            if (check!='') {
                $('filter_nass').checked=false;
                $('filter_trocken').checked=false;
                $('filter_snack').checked=false;
                $('filter_'+check).checked=true;
            }
        }*/
        return true;
    },    
    
    
    /*
        sets the dog-phase-text
    */
    displayDogPhase: function()
    {
        var size = $('result_rasse_input').value;
        
        this.checkInputNum('years');
        this.checkInputNum('month');
        
        var years = $('years').value;
        var month = $('month').value;
        this.dogPhaseName(this.dogPhaseValue(size,month,years))
    },
    
    checkInputNum: function(id){
        var value = $(id).value;
        var newVal = "";        
        for(var i=0; i < value.length; i++){
            var temp = value.substring(i, i+1);
            if(temp.test(/[0-9]/))
                newVal += temp;
        }
        $(id).value = newVal;
    },
    
    /*
        checks for the variables "age" and "product" in the query-string
    */
    setQsVariables: function()
    {
        var url = window.location.href;
        
        if (url.match(/[\?\&]level1=([0-4])/i)) {
            var temp = url.replace(/^.*[\?\&]level1=([0-4]).*$/i, '$1');
            this.slider.set(temp);
            temp = temp == 4 ? 2 : temp == 0 ? -1 : temp - 1;
            $('result_rasse_input').value = temp;
        }
        
        if (url.match(/[\?\&]level2=(welpe|adult|senior)/i)) {
            var tempAge = url.replace(/^.*[\?\&]level2=(welpe|adult|senior).*$/i, '$1');
            var ageId = 0;
            switch(tempAge){
                case 'welpe':
                    ageId = 1;
                    break;
                case 'adult':
                    ageId = 2;
                    break;
                case 'senior':
                    ageId = 3;
                    break;
            }
            this.qs_dogphase=ageId
            this.dogPhaseName(this.qs_dogphase);
        }
        if (url.match(/[\?\&]level3=(nass|trocken|snack|func_snack)/i)) {
            var check = url.match(/^.*[\?\&]level3=((nass|trocken|snack|func_snack)(;(nass|trocken|snack|func_snack)){0,2}).*$/i);            
            if (check!='') {
                $('filter_nass').checked=false;
                $('filter_trocken').checked=false;
                $('filter_snack').checked=false;
                $('filter_func_snack').checked=false;
                check[1].split(';').each(function(item){
                    $('filter_'+item).checked=true;
                });                
            }    
        }
        
        if (url.match(/[\?\&]years=([0-9]{1,})/i)) {
            var check = url.match(/^.*[\?\&]years=([0-9]{1,}).*$/i);            
            $('years').value = check[1];       
        }
        if (url.match(/[\?\&]month=([0-9]{1,})/i)) {
            var check = url.match(/^.*[\?\&]month=([0-9]{1,}).*$/i);            
            $('month').value = check[1];       
        }
        if (url.match(/[\?\&]dogname=(.*)/i)) {
            var check = url.match(/^.*[\?\&]dogname=(.*?)([\?\&]|$)/i);    
            $('dogname').value = check[1];       
        }
        
    },
    
    /*
        check request parameter    
    */
    checkParams : function()
    {
        if(window.location.search || window.location.hash != "") {
            $$('.food').addClass('hide');
            $$('.food_commendation').removeClass('hide');
        } else {
            $$('.food').removeClass('hide');
            $$('.food_commendation').addClass('hide');
        }
    },
    
    /*
        displays the loading animation and resets the current page
    */
    showLoading: function()
    {
        this.currentPage = 0;
        $('content').innerHTML = '<div style="margin:auto;text-align:center;padding-top:150px;"><img src="../Images/layout_rl/loading.gif" alt="" /></div>';
    },
    /*
        adds an event listener to the page-links
    */
    addPageSelectEvent: function (e) 
    {
        e.addEvent('click', function() {
            // using the instance here. is there a better way to achieve this?
            // bind actually makes it impossible to get the attribute...
            myCarrousel.loadPage(this.getAttribute("page"));
            return false;
        });
    },
    
    /*
        calculates and displays the current set of pages available
    */
    showPageSelection: function()
    {
        $('pageNumDisplay').innerHTML = '';        
        
        var firstA   = new Element('a', {'href': '#', 'title': 'mehr Details','page': Math.max(0,this.currentPage-1),'html': '<img src="./anc_products_back.gif" />', 'class': 'arrow'});
        this.addPageSelectEvent(firstA);
        $('pageNumDisplay').appendChild( firstA );
        
        this.pageNum=Math.ceil(this.ItemCountFiltered/this.maxItems);
        for (var i = 0;i<this.pageNum;i++) {
//            var text=this.currentPage==i-1?(i+1)+" \u2026 ":(i+1);
            var text=(i+1);
            var cl=this.currentPage==i?'active':'';
            var newA   = new Element('a', {'href': '#', 'title': 'mehr Details','page': i,'text': text, 'class': cl});
            this.addPageSelectEvent(newA);
            $('pageNumDisplay').appendChild( newA );
        }
        var lastA   = new Element('a', {'href': '#', 'title': 'mehr Details','page': Math.min((this.pageNum-1),(this.currentPage+1)),'html': '<img src="./anc_products_forward.gif" />', 'class': 'arrow'});
        this.addPageSelectEvent(lastA);
        $('pageNumDisplay').appendChild( lastA );
    },
    
    /*
        loads a specific page
    */
    loadPage: function(page)
    {
        this.currentPage = parseInt(page);
        this.update();
        this.buildAnchorURL();
    },
    /*
        handles the creation of the current product-page
    */
    update: function()
    {
        this.teaserText();
        var newUL = new Element('ul', {'id': 'carrousel_content'});
        this.ItemCount = 0;        
        this.ItemCountFiltered = 0;        
        
        this.data.filter(this.itemFilter,this).each(function(item){
            newUL = this.addItem(newUL, item );                
        },this);

        if( this.ItemCount <= 0 ) {
            $('dogteaser').innerHTML = 'In dieser Kategorie gibt es leider keine Produkte.';
        }

        this.showPageSelection();
        $('content').innerHTML = '';
        $('content').appendChild(newUL);
        $('content').appendChild(new Element('div', {'class': 'clr'}));
    },
    
    /*
        creates the sentence "wir empfehlen..."
    */
    teaserText: function()
    {
        var size = $('result_rasse_input').value;
        var years = $('years').value;
        var month = $('month').value;
        var name = $('dogname').value;
        name = name.replace(/<\/?[^>]+>/gi, '');
        var age = this.calcAge(month,years);
        var c_month = age%12;
        var c_years = Math.floor(age/12);
        var text = '';
        if (size>=0 || years>0 || month>0){
            if (name=='') {
                name='Ihr Hund';
            }
            text+=name;
            text+=' ist ';
            if (size>-1) {
                text+=' ein '+this.sizes[size]+' Hund';
            }
            if (size>-1 && (years>0 || month>0)) {
                text+=' und ';
            }
            if (c_years==1){
                text+=c_years+' Jahr ';
            }
            else if (c_years>1){
                text+=c_years+' Jahre ';
            }
            if (c_years>0 && c_month>0) {
                text+=' und ';
            }
            if (c_month==1){
                text+=c_month+' Monat ';
            }
            else if (c_month>1){
                text+=c_month+' Monate ';
            }
            if (month>0 || years>0) {
                text+=' alt. ';
            }
            else {
                text+='. ';
            }
            if (month>0 || years>0) {
                this.qs_dogphase=0;
                text+=' Er ist somit ein '+this.dogPhaseName(this.dogPhaseValue(size,month,years))+' und wir empfehlen für Ihn folgende Produkte.';
            }
            else {
                text+=' Wir empfehlen für Ihn folgende Produkte.';
            }
        }
        else if (size==-1 && !(month>0 || years>0)){
            text='Wir empfehlen '+name+' folgende Produkte.';
        }        
        $('dogteaser').innerHTML=text;
    },
    
    /*
        calculates the age in months
    */
    calcAge: function (month,year)
    {
        month=month>0?parseInt(month):0;
        year=year>0?parseInt(year):0;
        return (month+year*12);
    },
    
    /*
        calculates the phase the selected dog is currenty in.
        0 = undefined
        1 = welpe
        2 = adult
        3 = senior
    */
    dogPhaseValue: function (size,month,year)
    {
        size=size>=-1?parseInt(size):0;
        if (size==-1) {
            size=1;
        }
        var age=this.calcAge(month,year);
        var phase=0;
        if (age>0) {
            switch (size) {
                case 0:
                    if (age<9) phase=1;
                    else if (age<120) phase=2;
                    else if (age>0) phase=3;
                break;
                case 1:
                    if (age<9) phase=1;
                    else if (age<120) phase=2;
                    else if (age>0) phase=3;
                break;
                case 2:
                    if (age<18) phase=1;
                    else if (age<96) phase=2;
                    else if (age>0) phase=3;
                break;
            }
        }
        return phase;
    },
    
    /*
        returns the name of the dog's life-phase
    */
    dogPhaseName: function (phasenum)
    {
        var phase='undefiniert';
        switch (phasenum) {
            case 1:phase='Welpe';break;
            case 2:phase='Adult';break;
            case 3:phase='Senior';break;
            default:phase='';
        }
        $('result_age').innerHTML='<strong>'+phase+'</strong>';
        return phase;
    },
    
    /*
        makes sure that only the selected products show up. not more than maxItems per page
    */
    itemFilter: function(item, index)
    {
        var phase=this.dogPhaseValue($('result_rasse_input').value,$('month').value,$('years').value);
        if (this.qs_dogphase>0) {
            phase=this.qs_dogphase;
        }
        var size=$('result_rasse_input').value>=0?parseInt($('result_rasse_input').value)+1:0;
        if($('filter_'+item.type).checked && (size==0 || (size>=item.sizes.from && size<=item.sizes.to)) && (phase==0 || (phase>=item.ages.from && phase<=item.ages.to))){
            this.ItemCountFiltered++;
            //if(this.ItemCount < this.maxItems && (this.maxItems*(this.currentPage)) <= index){
            if(this.ItemCount < this.maxItems && (this.maxItems*(this.currentPage)) <= this.ItemCountFiltered){
                this.ItemCount++;
                return item;
            }
        }
    },
    
    /*
        creates the dom of a single product
    */
    addItem: function(parent, item)
    {    
        var newLi  = new Element('li', {'class': 'lt'});
        var divP   = new Element('div',{'class': 'prod_box_p'});
        var divImg = new Element('div',{'class': 'prod_box_img'});
        var divTxt = new Element('div',{'class': 'prod_box_txt', 'text': item.title});
        var divClr = new Element('div',{'class': 'clr'});
        divTxt.innerHTML = item.title;
        var newImg = new Element('img', {'src': this.imgPath+item.id+'.jpg' , 'alt': ''});
        
        newLi.appendChild( divP );
        divP.appendChild( divImg );
        divImg.appendChild( newImg );
        divP.appendChild( divTxt );
        if ($type(item.weights)=='object' && $type(item.weights.weight)=='string') {
            item.weights.weight=Array(item.weights.weight);
        }
        if ($type(item.weights)=='object' && $type(item.weights.weight)=='array') {
            var divOrg = new Element('div',{'class': 'prod_box_txt orange', 'text': "Erhältlich in den Größen:"});
            var divOrg2= new Element('div',{'class': 'prod_box_txt orange', 'text': item.weights.weight.join(', ')});
            divP.appendChild( divOrg );
            divP.appendChild( divOrg2 );
        }
    
        newLi.addEvent('click', function(){
            var query='';            
            window.location.href='produkte/data/2408_'+item.id+'.aspx'+query;
            return false;
        },this);
        divP.addEvent('mouseenter', function(){
            this.set('class','prod_box_a');
            return false;
        });
        divP.addEvent('mouseleave', function(){
            this.set('class','prod_box_p');
            return false;
        });
        
        parent.appendChild( newLi );
        return parent;
    },
    
    /*
        gets the product-data from the server
    */
    getDataFromXml: function()
    {
        var myRequest = new Request({    
            method:     'get', 
            url:         this.dataUrl,
            async:         false}
        ).send();
        
        var json = eval('(' + myRequest.response.text + ')');
        return json.data.products.product;
    },
    
    /*
        initializes the slider
    */
    initSlider: function ()
    {
        this.slider = new Slider($('slider_rasse'), $('slider_rasse').getElement('.knob'), {
            steps: 4,
            wheel: true,
             snap: false,
            onChange: function(value){
                switch(value){
                    case 0:
                        $('result_rasse').innerHTML = "<strong>keine Auswahl</strong>";
                        $('result_rasse_input').value = "-1";
                    break;                        
                    case 1:
                        $('result_rasse').innerHTML = "<strong>Klein</strong>";
                        $('result_rasse_input').value = "0";
                    break;
                    
                    case 2:
                        $('result_rasse').innerHTML = "<strong>Mittel</strong>";
                        $('result_rasse_input').value = "1";
                    break;
                    
                    case 3:
                        $('result_rasse').innerHTML = "<strong>Gro&szlig;</strong>";
                        $('result_rasse_input').value = "2";
                    break;
                }
            }
        });
    }
});
