/**
* Template for a js project.
* @author NOSE
*
* @version 1.1.0 initial version
*
*/
var BB = {
    marken       : new Array(),
    filter       : new Array(),
    filterBin    : new Array(),
    aSearch      : new Array(),
    aLang        : new Array(),
    lang         : "de",
    lastCat      : "id_0_0",
    lastDetail   : false,
    getAllBrands : false,
    startDate    : new Date(),
    startTime    : 0,
    jsonp        : false,
    jsonpath     : '',
    loaderimg    : '',
    /**
     * Initialize.
     */
    initialize : function () {
		  
		  DEBUG = false;
        
		  jQuery.log("initialize");
        // var date = new Date();
        BB.startTime = BB.startDate.getMilliseconds();
        // jQuery.log("StartTime: "+BB.startTime);
        jQuery("#locations").hide();
        
        /* Look if a language is given */
        if (jQuery(document).getUrlParam("lang")) {
            BB.lang = jQuery(document).getUrlParam("lang");
            jQuery.log("Language set to: '"+BB.lang+"'");
        }
        
        /* check the cookie */
        var cookie = jQuery.cookie("brandbrowser");
        if (typeof cookie != "undefined" && cookie != null) {
            BB.lastCat = cookie;
				if (BB.lastCat != "id_0_0") {
           		BB.getAllBrands = true;
				}
        }
        
        /* Look if a cat parameter is given */
        if (jQuery(document).getUrlParam("cat")) {
            BB.lastCat = jQuery(document).getUrlParam("cat");
            BB.getAllBrands = true;
		      jQuery.cookie("brandbrowser", BB.lastCat);
        }
        
        /* Start to load the language sensitive text */
        BB.langLoader();
        
        /* Show the loading animation */    
        jQuery("#brandnav").append("<div id='navloadindicator' style='text-align: center; margin-top:50px;'><img src='"+BB.loaderimg+"'/></div>");     
        jQuery("#brandsHolder").append("<div id='brandloadindicator' style='text-align: center; margin-top:50px;'><img src='"+BB.loaderimg+"'/></div>");     
        
        
    },
    /**
    * load the language text.
    */
    langLoader : function () {
		  var jsonCall = 'json';
        var obj = new Object();
        obj['request'] = 'lang';
        obj['lang'] = BB.lang;
        if (BB.jsonp) {
            obj['jsoncallback'] = '?';
			jsonCall = 'jsonp';
        }

        $.ajax({
          dataType: jsonCall,
          data: obj,
          url: BB.jsonpath,
          success: function (data) {
				    BB.aLang = data;
                BB.filterLoader();
                jQuery("#brandsFilter")
                    .focus(function(){
                        /* Inititalize text filtering */
                        var options = {
                            callback: function (txt) {
                                BB.showbrands(txt);
                            },
                            wait:500
                        }
                        jQuery(this).val('').removeClass("disabled").typeWatch(options);
                        BB.clearSelection();
                    })
                    .blur(function(){
                        if (jQuery(this).val() == '') {
                            if (!jQuery(this).hasClass("disabled")) {
                                jQuery(this).addClass("disabled");
                            }
                            jQuery(this).val(BB.aLang.searchBrands);
                        }
                    })
                    .addClass("disabled")
                    .val(BB.aLang.searchBrands);
               BB.locLoader();
          },
		error: function(xhr){
			    alert('Request Status langLoader: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
		}
        });
    },
    /**
    * load the location items.
    */
    locLoader : function () {
		  var jsonCall = 'json';
        var obj = new Object();
        obj['request'] = 'loc';
        obj['lang'] = BB.lang;
        if (BB.jsonp) {
            obj['jsoncallback'] = '?';
				jsonCall = 'jsonp';
        }
        $.ajax({
          dataType: jsonCall,
          data: obj,
          url: BB.jsonpath,
          success: function (data) {
                jQuery("#locations").append(BB.buildLocations(data));
                // jQuery.log("Locations loaded after "+getLoadTime(BB.startTime)+"ms.");
          },
		  error: function(xhr){
			    alert('Request Status locLoader: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
		  }
        });
    },
    setFilter : function () {
        var vCat = BB.lastCat.split('_');
        BB.filterBin[vCat[1]] = 1;
		jQuery.cookie("menutree", BB.filterBin.join("") );
		jQuery.cookie("brandbrowser", '', { expires: - 1 });
    },
    /**
    * load the section navigation.
    */
    filterLoader : function () {
		var jsonCall = 'json';
        var obj = new Object();
        obj['request'] = 'filter';
        obj['lang'] = BB.lang;
        if (BB.jsonp) {
            obj['jsoncallback'] = '?';
			jsonCall = 'jsonp';
        }
        $.ajax({
          dataType: jsonCall,
          data: obj,
          url: BB.jsonpath,
          success: function (data) {
                BB.filter = data;
                jQuery("#brandnav").append(BB.buildNav()).removeClass("watermark");
                
                /* set the last active class */
                var e = jQuery("#"+BB.lastCat).parent();
		        var liActive = $("li").index(e[0]);
		        $.cookie("menuactive", liActive);
		        
		        /* initialize the filter navigation */
                jQuery("#browser").menutree({
			        collapsed: true,
			        unique: true,
			        persist: "cookie",
			        animated: "fast",
			        fixfirst: true
		        });
		        // jQuery.log("Section Navigation loaded after "+getLoadTime(BB.startTime)+"ms.");
          },
          error: function(xhr){
			    alert('Request Status filterLoader: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
		  }
        });
    },
    buildNav : function () {
        BB.filterBin[0] = '1';
        var vRet = '<ul id="browser" class="mTop4em">';
        vRet += '<li class="open">';
		  vRet += '<span id="id_0_0" onclick="BB.filterbrands(\'id_0_0\');">';
		  vRet += BB.aLang.allBrands;
		  vRet += '<\/span>';
		  vRet += '<ul>';
        var vOpen = false;
        jQuery.each(BB.filter, function(i,item){
            var aID =  i.split("_");
            if (aID[2] == 0 && vOpen) {
			    vRet += '<\/ul>';
                vRet += '<\/li>';
            }
            vRet += '<li>';
            vRet += '<span id="'+i+'" onclick="BB.filterbrands(\''+i+'\');">'+item+'<\/span>';
            if (aID[2] == 0) {
                BB.filterBin[BB.filterBin.length] = '0';
			    vRet += '<ul>';
			    vOpen = true;
            } else {
                vRet += '<\/li>';
            }
        });
        if (vOpen) {
            vRet += '<\/li>';
        }
        vRet += '<\/ul>';
        vRet += '<\/li>';
        vRet += '<\/ul>';
        
        BB.setFilter();
        BB.brandsLoader();
        jQuery("#navloadindicator").remove();
        return vRet;
    },
    /**
    * load the location items.
    */
    brandsLoader : function () {
		  var jsonCall = 'json';
        var obj = new Object();
            obj['request'] = 'brand';
            obj['lang'] = BB.lang;
        if (BB.getAllBrands) {
            obj['cat'] = BB.lastCat;
        }
        if (BB.jsonp) {
            obj['jsoncallback'] = '?';
				jsonCall = 'jsonp';
        }
        $.ajax({
          dataType: jsonCall,
          data: obj,
          url: BB.jsonpath,
          success: function (data) {
                BB.marken = data;
                BB.brandsLoaded();
          }
        });
    },
    /**
    * brands xml loaded.
    */
    brandsLoaded : function () {
        BB.filterbrands(BB.lastCat);
		 //  jQuery.log("Brands loaded after "+getLoadTime(BB.startTime)+"ms.");
		  jQuery("#brandsFilter").parent().removeClass("watermark");
        jQuery("#brandloadindicator").remove();
    },
    showDetail : function (e, i, t, s, c, l, u) {
        BB.clearSelection();
        
        /* set clicked brand to active */
        BB.lastDetail = e.id;
        jQuery("#"+BB.lastDetail).addClass('active');
        
        var vRet = '<h3 class="noBottomBorder">' + unescape(t) + '</h3>';
        vRet += '<p class="fontSmall">' + unescape(s) + '</p>';
        vRet += '<p class="alignCenter"><img src="' + i + '" alt="' + unescape(t) + '" /></p>';
        if (typeof u != "undefined" && u != '') {
            vRet += '<a class="button posAbsBottomRight" href="'+u+'" target="_parent">';
            vRet += '<span>'+BB.aLang.goDetail+'</span>';
            vRet += '</a>';
        }
        jQuery("#onebrand").parent().removeClass("watermark");
        jQuery("#onebrand").html(vRet).show();
        jQuery("h3", ".accordeon")
            .removeClass("toggler")
            .removeClass("expanded")
            .addClass("collapsed")
            .addClass("inactive")
            .removeAttr("style")
            .unbind()
            .next()
                .addClass("hidden")
                .removeAttr("style")
                .removeClass("item");
        
        var vLoc = l.split(',');
        for (var i = 0; i < vLoc.length; i++) {
            jQuery("h3", "#" + vLoc[i])
                .removeClass("inactive")
                .addClass("toggler")
                .next()
                    .removeClass("hidden")
                    .addClass("item");
        }
        jQuery("#locations").parent().removeClass("watermark");
        jQuery("#locations")
            .itemToggler({
			    selectorToggler: "h3.toggler",
                accordion:true
            })
            .show();
    },
    clearSelection : function () {
        /* reset the last clicked brand */
        if (BB.lastDetail) {
            jQuery("#"+BB.lastDetail).removeClass('active');
        }
        BB.lastDetail = "";
        /* reset the detail and locations */
        jQuery("#onebrand").hide().parent().addClass("watermark");
        jQuery("#locations").hide().parent().addClass("watermark");
    },
    showbrands : function (e) {
        var vCount = 0;
        var vRet = '<ul id="brands">';
        
        var vCat = BB.lastCat.split('_');
        var c = vCat[1];
        var s = vCat[2];
        
		  /*
        if ((c != 0) && (s == 0)) {
            vResult = BB.aLang.inside; // + " " + BB.filter["id_"+vCat[1]+"_0"];
            vClaim = vClaim + " " + vResult;
        } else if ((c != 0) && (s != 0)) {
            vResult = BB.aLang.inside; // + " " + BB.filter["id_"+vCat[1]+"_0"]+" - "+BB.filter[BB.lastCat];
            vClaim = vClaim + " " + vResult;
        }
        */
        
        jQuery.each(BB.aSearch, function(i,item){
            var vImgURL = item.logo;
            var vBrandURL = item.link;
            var vTitel = item.name;
            var vCat = item.nav.split("_");
            var vST = "id_"+vCat[1]+"_"+vCat[2];
            var vT = "id_"+vCat[1]+"_0";
            var vSubtitle = BB.filter[vT];
            if (vT != vST) {
                vSubtitle += " - "+BB.filter[vST];
            }
            var vLoc = new Array();
            jQuery(item.locations).each(function (e) {
                vLoc.push(this);
            });
            var vTXT = vTitel.toUpperCase();
            if ((typeof e == 'string' && (vTXT.indexOf(e.toUpperCase()) != - 1)) || (typeof e == 'undefined')) {
                vCount++;
                vRet += BB.addAbrand(vImgURL, escape(vTitel), escape(vSubtitle), vCat[1]+"_"+vCat[2]+"_"+i, vLoc, vBrandURL);
            }
        });
        vRet += '</ul>';
		  /*
        if (vCount == 0) {
            var vResultTxt = BB.aLang.noResult.replace(/&1/g, '"'+e+'"');
            jQuery("#brandsCounter").html(vResultTxt);
        } else {
            jQuery("#brandsCounter").html(vCount + vClaim);
        }
		  */
		if (vCount == 0) {
            var vResultTxt = BB.aLang.noResultsInBrands;
		    if (c != 0) {
		       vResultTxt = BB.aLang.noResultsInCat;
			}
            jQuery("#brandsCounter").html(vResultTxt);
        } else {
			var vClaim = " " + BB.aLang.brandsInAllBrands;
			if (c != 0) {
		  		vClaim = " " + BB.aLang.brandsInCat;
			}
            jQuery("#brandsCounter").html(vCount + vClaim);
        }
        jQuery("#brandsHolder").html(vRet);
    },
    filterbrands : function (e) {
        BB.clearSelection();
        
        if (jQuery("#brandsFilter").val() != BB.aLang.searchBrands) {
            if (!jQuery("#brandsFilter").hasClass("disabled")) {
                jQuery("#brandsFilter").addClass("disabled");
            }
            jQuery("#brandsFilter").val(BB.aLang.searchBrands);
        }
        BB.lastCat = e;
        jQuery.cookie("brandbrowser", BB.lastCat);
        
        var vCat = BB.lastCat.split('_');
        var c = vCat[1];
        var s = vCat[2];
        
        BB.aSearch = [];
        jQuery.each(BB.marken, function(i,item){
            var vCat = item.nav.split("_");
            var vST = "id_"+vCat[1]+"_"+vCat[2];
            var vT = "id_"+vCat[1]+"_0";
            
            if (typeof c != "undefined" && s == 0) {
                if (vCat[1] == c || c == 0) {
                    BB.aSearch.push(this);
                }
            } else if (typeof c != "undefined" && s != 0) {
                if (vCat[1] == c && vCat[2] == s) {
                    BB.aSearch.push(this);
                }
            } else {
                BB.aSearch.push(this);
            }
        });
        
        if (BB.getAllBrands) {
            BB.getAllBrands = false;
            BB.brandsLoader();
        }
        BB.showbrands();
    },
    buildLocations : function (data) {
        var vRet = '<h3>'+BB.aLang.availableIn+'</h3>';
        
        jQuery.each(data, function(i,item){
            vRet += '<div class="accordeon" id="'+item.id+'">';
            vRet += '<h3 class="head">'+item.name+'</h3>';
			vRet += '<div class="item">';
			vRet += '<p>'+item.adS+'<br/>';
			vRet += item.adO+'<br/>';
			vRet += item.adT+'<\/p>';
			vRet += '<table>';
			vRet += '<caption>'+BB.aLang.openingHours+'</caption>';
			for (i=0;i<jQuery(item.adD).length;i++) {
			    vRet += '<tr>';
			    vRet += '<th scope="row">'+item.adD[i][0]+'</th>';
			    vRet += '<td>'+item.adD[i][1]+'</td>';
			    vRet += '</tr>';
			}
			vRet += '<\/table>';
            vRet += '<\/div>';
            vRet += '<\/div>';
        });
        return vRet;
    },
    addAbrand : function (i, t, s, c, l, u) {
        return '<li id="dt_'+c+'" onclick="BB.showDetail(this, \'' + i + '\', \'' + t + '\', \'' + s + '\', \'' + c + '\', \'' + l + '\', \'' + u + '\');">' + unescape(t) + '<span class="category">' + unescape(s) + '</span></li>';
    },
    resetSearch : function () {
        jQuery("#brandsFilter").val('');
        BB.filterbrands(BB.lastCat);
    }
};

jQuery(document).ready(function () {
	window.setTimeout("BB.initialize()", 200);
});
jQuery(window).load(function () {
});
function sortByID(a, b) {
        var x = a.id;
        var y = b.id;
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortFilterNav(a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
function sortNum(a, b) {
        return a - b;
}
function getLoadTime(t) {
    var date = new Date();
	 var vSec = date.getMilliseconds();
	 var vRes = (vSec - t);
    return vRes;
}
