$(document).ready(function() {
    // init product filter
    PFilter.init();

    //brands
    $("#brands-container").each(function() {
        $(".br-content").hide();
        $(".brands-article h3").click(function() {
            $(".br-content").hide(250);
            $(this).parent().children(".br-content").show(500);
        });
        $(".brands-article a").click(function() {
            $(".br-content").hide(500);
        });
    });

    // social media buttons
    $("#SM-buttons img").hover(function() {
        $(this).attr("oldSrc", this.src);
        $(this).attr("src", this.src.replace(/_off.png/, "_on.png"));
    }, function() {
        $(this).attr("src", $(this).attr("oldSrc"));
    });

   // print (for news article, called from flash)
   var print = getUrlParameter('print');
   if(print == 'true'){
      window.print();
   }

   // news room
      $('.newsarticleshare').hover(function(){
          $('#share-links').show();
          $('.newsarticledownload').css('top', '-143px');
        }, function(){
          $('#share-links').hide();
          $('.newsarticledownload').css('top', '0px');
        });
      $('#share-links-fb').hover(function(){
        $('#share-links-fb img').attr('src', $('#share-links-fb img').attr('src').replace('_off', '_on'));
      }, function(){
        $('#share-links-fb img').attr('src', $('#share-links-fb img').attr('src').replace('_on', '_off'));
      });
      
      $('#share-links-digg').hover(function(){
        $('#share-links-digg img').attr('src', $('#share-links-digg img').attr('src').replace('_off', '_on'));
      }, function(){
        $('#share-links-digg img').attr('src', $('#share-links-digg img').attr('src').replace('_on', '_off'));
      });
      
      $('#share-links-delicious').hover(function(){
        $('#share-links-delicious img').attr('src', $('#share-links-delicious img').attr('src').replace('_off', '_on'));
      }, function(){
        $('#share-links-delicious img').attr('src', $('#share-links-delicious img').attr('src').replace('_on', '_off'));
      });
      
      $('#share-links-mail').hover(function(){
        $('#share-links-mail img').attr('src', $('#share-links-mail img').attr('src').replace('_off', '_on'));
      }, function(){
        $('#share-links-mail img').attr('src', $('#share-links-mail img').attr('src').replace('_on', '_off'));
      });

    //project filter
    $("#project-filter input").each(function() {
        var id = $(this).attr("id").substring(2).split("-");
        var cat = id[0];
        var filter = id[1];
        
        if(filter != "all")
            $(this).removeAttr("checked");
        
         if(!$(this).attr("checked"))
            $(this).next().addClass("disabled");
        
    });

    $("#project-filter").each(function() {
  
        $("#project-filter input").click(function() {
            var id = $(this).attr("id").substring(2).split("-");
            var cat = id[0];
            var filter = id[1];
            
            /* interface usabilty: enable/disable boxes */
            //check 'all' if nothing selected
            var nothingSelected = false;
            var allBox = $(this).parent().parent().find("input:first");
            var boxesChecked = $(this).parent().parent().find("input:checked").length;
            if (boxesChecked == 0 || (boxesChecked == 1 && allBox.attr("checked"))) {
                nothingSelected = true;
                //disable others
                $(this).parent().parent().find("input").each(function() {
                    $(this).next().addClass("disabled");
                });
                //enable 'all' box
                allBox.attr("checked","checked");
                allBox.next().removeClass("disabled");
            }
            
            //enable/disable check boxes
            if (filter != "all") {
                if(!nothingSelected) {
                    //enable other checkboxes
                    $(this).parent().parent().find("input").each(function() {
                        $(this).next().removeClass("disabled");
                    });
                
                    //disable  'all' box
                    allBox.removeAttr("checked");
                    allBox.next().addClass("disabled");  
                }     
            } else {
                if($(this).attr("checked")) {
                    //disable all other checkboxes
                    $(this).parent().parent().find("input").each(function() {
                        $(this).next().addClass("disabled");
                    });
                    $(this).next().removeClass("disabled");
                } else {
                    //enable all other checkboxes
                    $(this).parent().parent().find("input").each(function() {
                        $(this).next().removeClass("disabled");
                    });
                    $(this).next().addClass("disabled");
                }                    
            }
       
            // fadeIn/Out matching projects
            $("#project-list li").each(function() {
               var project = $(this);
               
                // iterate filters  categories
                var showProduct = true;
                    
                $("#project-filter > div.col").each(function() {
                    filterPassed = false;
                
                    $(this).find("input:checked").each(function() {
                        id = $(this).attr("id").substring(2).split("-");
                        cat = id[0];
                        filter = id[1];
                        if ((filter == "all") || (project.attr(cat+"-"+filter))) {
                            filterPassed = true;
                        }
                    });
    
                    if(filterPassed == false)
                        showProduct = false;
                });
                
                if (showProduct) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });

            return;
        });   
    });
    
    //downloads
    $("#download-container").each(function() {
        $(".br-content").hide();
        $(".download-article h3").click(function() {
            $(".br-content").hide(250);
            $(this).parent().children(".br-content").show(500);
        });
    });
    
    //contactform
    $("#contact").each(function() {
        $(".brc").hide();
        $("#architect").click(function() {
          $(".brc").hide(250);
            $(this).parent().children(".br-content").show(500);
        });
        $("#designer").click(function() {
            $(".brc").hide(250);
            $(this).parent().children(".br-content2").show(500);
        });
        $("#dealer").click(function() {
            $(".brc").hide(250);
            $(this).parent().children(".br-content3").show(500);
        });  
        $("#other").click(function() {
            $(".brc").hide(250);
        });
    });

    // Fancybox
    $("a.zoom").fancybox();
    $("a.zoom1").fancybox({
        'overlayOpacity'    :   0.7,
        'overlayColor'      :   '#FFF'
    });
    $("a.zoom2").fancybox({
        'zoomSpeedIn'       :   500,
        'zoomSpeedOut'      :   500
    });
    

  $("a#inline").fancybox({
  'hideOnContentClick': true
  });
  $("a.group").fancybox({
  'zoomSpeedIn': 300,
  'zoomSpeedOut': 300,
  'overlayShow': true,
  'imageScale': 500,
  'frameWidth': 1000,
  'frameHeight': 600
  });

    //bg image
    BUAUtils.bgimage();
    //retailers
    $("#countries").change(function() {
        if ($(this).val() == "nil") {
            $(".category").show();
      var _obj = $("#cities option:first-child").clone();
      $("#cities").children().remove();
      $("#cities").append(_obj);
      $("#cities").hide();
            $("#retailers").empty();
            return;
        }
    
        $("#retailers").empty();
    $.get("/Content.Node/mobile/cities.php", {"country": $(this).val(), "categoryid": RS.getCategory()}, RS.renderCities, "json")
    });

    $(".rtf-submit").live("click",function() {
        if ($(".rtf-text").val() == "") {
            $(".category").show();
      var _obj = $("#cities option:first-child").clone();
      $("#cities").children().remove();
      $("#cities").append(_obj);
      $("#cities").hide();
            $("#retailers").empty();
            return false;
        }
        
        RS.getRetailersBySearch($(".rtf-text").val(),true);
        return false;
    });
    
    $(".rtf-middle input").bind("change",function() {
    RS.updateCheckboxes($(this).attr("id"), $(this).attr("checked"));
    
        $("#retailers").empty();
        if ($("#countries").val() == "nil") {
            $(".category").show();
      var _obj = $("#cities option:first-child").clone();
      $("#cities").children().remove();
      $("#cities").append(_obj);
      $("#cities").hide();
            $("#retailers").empty();
            return;
        }
    var city = $("#cities").val();
    if(city == "nil")
      city = "";
        RS.getRetailers($("#countries").val(), city, RS.getCategoryInputChecksums(), true);
    });

    $("#cities").live("change", function() {
        if ($(this).val() == "nil") return;
        
        RS.getRetailers($("#countries").val(), $(this).val(), RS.getCategoryInputChecksums(), true);
    });
});

window.onresize = function() { BUAUtils.bgimage() };

var PFilter = {
    filterGroups: [],
    
    init: function() {
      // read cookie
    var sChecked = "";
    sChecked = getCookie("prodsearch");
    var aChecked = sChecked.split("|");

    for (var lCount in aChecked) {
      $("input[value=" + aChecked[lCount] + "]").attr("checked", "checked");
    }
    
    PFilter.collect();
    PFilter.calculate();
      
        // products back links
        $(".project-filter-back a").live("click", function() {
            if (document.referrer && document.referrer.indexOf("/Content.Node/search/productsearch/") > -1) {
                history.back();
                return false;
            }
            return true;
        });

        $("#P-reset-search").live("click", function() {
            $("#P-filter-form").get(0).reset();
            PFilter.collect();
            PFilter.calculate();
            return false;
        });

        $("#P-filter-form fieldset input").click(function() {
            PFilter.collect(($(this)));
            PFilter.calculate();
        });
        
        $("#P-filter-region-international, #P-filter-region-us").click(function() {
            location.href = location.pathname + "?region=" + $(this).val();
        });

        // product filter menu
        $("#P-filter-menu a").live("click", function() {
            $("#P-filter-menu, #P-filter-form").animate({
                left: "-=500"
            }, 350, function() {
                $("#P-filter-menu, #P-filter-form").hide();
            });
            $("#nav-main.P-filter").fadeIn(500);
            
            return false;
        });

    },
    
    collect: function(clickedElem) {
        // clear filters
    var sChecked = "";
    PFilter.filterGroups = [];
    $("#P-filter-form fieldset").each(function() {
            var checksumMask = parseInt($(this).attr("checksumMask"));
            var clickedElemChecksumMask = (clickedElem != undefined) ? parseInt(clickedElem.parent().parent().attr("checksumMask")) : -1;
            
            var allBox = ($(this).find("label:first input"));
      var allBoxChecked = allBox.attr("checked");
            
            //if option is clicked, deselect 'all'
            if((clickedElemChecksumMask == checksumMask) && (clickedElem.val() != checksumMask)) {
                allBox.removeAttr("checked");
                allBoxChecked = false;
            }
      
            //iterate check-boxes
            var currentFilterChecksum = 0;
            $(this).find("input:checked").each(function() {
                var inputCheckSum = parseInt($(this).val());
          
                //calculate filter sum
                if($(this).attr("checked")) {
                    if (sChecked != "") {
                        sChecked = sChecked + "|";
                    }
                    sChecked = sChecked + inputCheckSum;                
                    currentFilterChecksum += inputCheckSum;
                }  
            });
                
            //correct checksum if 'all' is selected
            if(currentFilterChecksum > checksumMask) {
                currentFilterChecksum = checksumMask;
            }
          
            //if nothing selected, select 'all'
            if(currentFilterChecksum == 0) {
                allBox.attr("checked","checked");
                currentFilterChecksum = checksumMask;
                allBoxChecked = true;
            }
      
            //interface usability: enable/disable boxes               
            $(this).find("input").each(function() {        
                //if 'all' checked disable checkboxes
                if(allBoxChecked) {
                    $(this).parent().addClass("disabled");
                }
                else {
                    $(this).parent().removeClass("disabled");
                }
            });      
            
            if(allBoxChecked) {
                allBox.parent().removeClass("disabled");
            } else {
                allBox.parent().addClass("disabled");
            }
        
            //store filter settings
            var maskObj = {};
            maskObj.checksumMask = checksumMask;
            maskObj.currentFilterChecksum = currentFilterChecksum;

            PFilter.filterGroups.push(maskObj);
    });
    
    setCookie("prodsearch",sChecked,1)
    },
    
    calculate: function() {
        var list = [];
        $("#P-filter-list li").each(function() {
            if (PFilter.filterGroups.length >= 1) {
                var isIncluded = true;
        
        //apply filters
                for (var i = 0; (i < PFilter.filterGroups.length) && isIncluded; i++) {
                    var filterGroup = PFilter.filterGroups[i];
                    var productChecksum = parseInt($(this).attr("checksum"));
    
                    /*old solution --> not beautiful ;)
          if ((!((productChecksum & filterGroup.checksumMask) & filterGroup.currentFilterChecksum) && filterGroup.currentFilterChecksum)) {
            isIncluded = false;
          } */
          
          //filter out non-matching products
          if((productChecksum & filterGroup.currentFilterChecksum) == 0) {
            isIncluded = false;
          }
                }
        
        //show/hide products
        if (isIncluded) {
          $(this).fadeIn(500);
          list.push($(this));
                } else {
          $(this).fadeOut(500);
        }        
            } else {
                $(this).fadeIn(500);
                list.push($(this));
            }
        });

        $("#content-P-filter h3 span").html(list.length);
    }
}

var BUAUtils = {
    bgimage: function() {
        $("#bg-image").each(function() {
            var ww = $(window).width();
            var wh = $(window).height();
            var cw, ch;

            $("#ov").height(wh);

            if (ww > 1000) {
                cw = (ww > 1000) ? ww : 1000;
                ch = "auto";
            } else {
                cw = "auto";
                ch = (wh > 580) ? wh : 580;
            }
            $("#bg-image img").width(cw).height(ch);
        });
    }
}
var RS = {
    renderCities: function(data) {
    var _obj = $("#cities option:first-child").clone();
    $("#cities").children().remove();
    $("#cities").append(_obj);
    
        if (data.cities.length <= 1) {
      $("#cities").hide();
            $(".category").hide();
            for (c in data.cities) {
                $("#catlabel-" + data.cities[c].category).show();
                RS.getRetailers($("#countries").val(), data.cities[c].name, RS.getCategoryInputChecksums(), false);
            }
            return;
        }

    $("#cities").show();
        
        $(".category").hide();
        for (c in data.cities) {
            $("#catlabel-" + data.cities[c].category).show();
            $("#cities").append('<option class="c-'+data.cities[c].category+'" >' + data.cities[c].name + '</option>');
        }
    },
    
    getCategoryInputChecksums: function() {
    var checksums = [];
        $(".rtf-middle input").each(function(index) {
            if($(this).is(":checked")) {
                if(index === 0) {
          checksums.push(RS.getCategory());
                    return checksums;
                } else {
          checksums.push(RS.getCategory() + parseInt($(this).val()));
                }
            }
        });
        return checksums;
    },
  
  getCategoriesFromChecksum: function(checksum) {
    var cats = [];
    var currentValue = parseInt(checksum);
    var binary = parseInt(checksum).toString(2);
    
    for(var i = binary.length; i > 0; i--) {
      var catId = currentValue & (Math.pow(2, i - 1));
      if (catId > 0)
      {
        cats.push(catId);
      }
      currentValue = currentValue % (Math.pow(2, i-1));
    }
    return cats;
  },
  
  updateCheckboxes: function(changedCheckboxId, checked) {
    var allUnchecked = true;
    $(".rtf-middle input").each(function(index) {
      if($(this).is(":checked"))
      {
        allUnchecked = false;
      }
    });
    
    if(allUnchecked == true)  // check checkbox all
    {
      $(".rtf-middle input").each(function(index) {
        if(index == 0)  // checkbox all
        {
          $(this).attr("checked", true);
        }
      });
      return;
    }
    
    if(changedCheckboxId == "all" && checked == true)
    {
      $(".rtf-middle input").each(function(index) {
        if(index != 0)  // any other checkbox than all
        {
          $(this).attr("checked", false);
        }
      });
    }
    else {
      $(".rtf-middle input").each(function(index) {
        if(index == 0)  // checkbox all
        {
          $(this).attr("checked", false);
        }
      });
    }
  },
    
    getRetailers: function(country, city, categoryChecksums, clearRetailers) {
        var data = {};
        data.country = country;
        if (city != "") {
            data.city = city;
        }
        
        if(categoryChecksums && categoryChecksums.length > 0) {
      var categoryId = categoryChecksums[0];
      for(var i=1; i<categoryChecksums.length; i++)
      {
        categoryId += ","+categoryChecksums[i];
      }
            data.categoryid = categoryId;
        }
        
        if (clearRetailers == true) {
            $("#retailers").empty();
        }

        $.get("/Content.Node/mobile/retailers.php", data, RS.renderRetailers, "json")
    },
    
    getRetailersBySearch: function(search, clearRetailers) {
        var data = {};
        data.search = search;
        /*if (city != "") {
            data.city = city;
        }*/
        
        if (clearRetailers == true) {
            $("#retailers").empty();
        }

        $.get("/Content.Node/mobile/retailers.php", data, RS.renderRetailers, "json")
    },
    
    renderRetailers: function(data, clear) {
        if (data.retailers.length == 0) return;
        
        for (var r in data.retailers) {
            RS.renderRetailer(data.retailers[r]);
        }
        //RS.filterRetailers();
        // http://maps.google.com/?&q=637%20Royal%20Street,%20New%20Orleans(Fischer-%20Gambino)&t=m&ie=unicode32&mrt=loc
    },

    renderRetailer: function(data) {
        if (!data) return;
        
    // $$$$$ RS.getCategoriesFromChecksum(data.category)
    
        var retailer = $("<div>").attr("id", "ret-" + data.id).addClass("retailer retcat-" + data.category).appendTo("#retailers");
        var left   = $("<div>").addClass("rtlr-left");
        var middle = $("<div>").addClass("rtlr-middle");
        var right  = $("<div>").addClass("rtlr-right");
        
        $("<div>").addClass("company").html(data.company).appendTo(left);
        //$("<div>").addClass("company2").html(data.company2).appendTo(retailer);
        $("<div>").addClass("street").html(data.street).appendTo(left);
        $("<div>").addClass("city").html(data.zip + " " + data.city).appendTo(left);
        $("<div>").addClass("phone").html(data.phone).appendTo(middle);
        $("<div>").addClass("phone2").html(data.phone2).appendTo(middle);
        $("<a>").addClass("email").html(data.email).attr({"href": "mailto:" + data.email}).appendTo(right);
        if (data.web.indexOf("http://") > -1) {
            data.web = data.web.substring(7);
        }
        $("<a>").addClass("web").html(data.web).attr({"target": "_blank", "href": "http://" + data.web}).appendTo(right);
        $("<a>").addClass("map").html("Map").attr({"target": "_blank", "href": "http://maps.google.com/?&q=" + escape(data.street + " " + data.city + "(" + data.company + ")") + "&t=m&ie=unicode32&mrt=loc"}).appendTo(right);
        
        retailer.append(left);
        retailer.append(middle);
        retailer.append(right);
        
        if(right.height()> left.height()) {
            left.height(right.height());        
        }
    },
    
    filterRetailers: function() {
        $(".retailer").hide();
        var c = RS.getCategory();
        if (c == 1) {
            $(".retcat-1, .retcat-3").show();
        } else if (c == 2) {
            $(".retcat-2, .retcat-3").show();
        } else {
            $(".retaler").show();
        }
    },
    
    getCategory: function() {
        if ($("#countries.alp").length == 1) {
            return 2;
        }
        return 1;
    }
}

/**
 * socialComment
 * @param type; site to which to post, valid values: "facebook", "twitter", "delicious" (required)
 * @param url; url to post, required for facebook and delicous, ignored by twitter (required/optional)
 * @param title; status for twitter, title for delicous, ignored by facebook (required/optional)
 **/
function socialComment(type, url, title) {
    var u = encodeURIComponent(url);
    var t = encodeURIComponent(title);
    var options = "";

    var s, w, h;
    switch (type) {
        case "facebook":
            w = 626;
            h = 436;
            s = "http://www.facebook.com/sharer.php?u=" + u + "&t=" + t;
            break;
        case "twitter":
            w = 780;
            h = 500;
            s = "http://twitter.com/home?status=" + t;
            break;
        case "delicious":
            w = 780;
            h = 550;
            s = "http://delicious.com/save?v=5&noui&jump=close&url=" + u + "&title=" + t;
            break;
        case "digg":
            w = 960;
            h = 550;
            s = "http://digg.com/submit?url=" + u + "&title=" + t + "&topic=design";
            options = ",scrollbars=1,resizable=1";
            break;
        default:
            return;
            break;
    }

    window.open(s, type, "toolbar=0,status=0,width=" + w + ",height=" + h + options);
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1)
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function getUrlParameter(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function setCookie( name, value, expires, path, domain, secure ) {
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );

  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }

  var expires_date = new Date( today.getTime() + (expires) );

  document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}
