////////////////////////////////////////////////////////////////////////////////
// InsightSPI Javascript Namespace. Copyright 2011 InsightSPI
////////////////////////////////////////////////////////////////////////////////
var ispi = {
    
  /* Menu */
  initialMenuSpritePosition:     "",
  menuSpriteOffset:              -70,
  currentMenuItemIdx:            0,
  dropDownHBuffer:               10,
  
  /* Home Promos */
  currentHomePromoIdx:           1,
  maxHomePromoIdx:               0,
  homePromoIntervalMilliSeconds: 7000,
  homePromoInterval:             "",
  homePromoActive:               true,
  
  /* Home Folders */
  homeFolderSpriteOffset:        330,
  
  /* Logo Grid */
  logoGridIntervalMilliSeconds:  3000,
  logoGridInterval:              "",
    
  /* Conditionally initialize the various bits of JS for the site. */
  init : function() {
    //Always initialize the menu
    ispi.initMenu();
    
    //Only initialize the home page elements when the home page is accessed
    if(ispi.selectorPresent("#homeContentArea")) {
      ispi.initHomePromos();
      ispi.initHomeFolders();
      ispi.initHomePageHouseGfx();
    }

    //Only initialize the form elements wieh a form page is accessed    
    if(ispi.selectorPresent("#requestMoreInfoDiv")) {
      ispi.initForms();
    }
    
    //Only initialize the logo grid elements when a page including the
    //logo grid is accessed
    if(ispi.selectorPresent("#logoGrid")) {
      ispi.initLogoGrid();
    }
    
    if(ispi.selectorPresent("#house_gfx")) {
      ispi.initSolutionsHouseGfx();
    }
  },
  
  /* Check if a selector is present on the current page's DOM */
  selectorPresent: function(selector) {
    return $(selector).length > 0;
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Home Page House Gfx
  //////////////////////////////////////////////////////////////////////////////
  initHomePageHouseGfx: function() {
    //Home page house graphic
    $("#home_house_gfx #industries a").mouseover(function() {
      var id = $(this).attr("id");
      var overId = id + "_over";
      $("#"+overId).show();
    }).mouseout(function() {
      var id = $(this).attr("id");
      var overId = id + "_over";
      $("#"+overId).hide();        
    });    
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Soltuions House Gfx
  //////////////////////////////////////////////////////////////////////////////
  initSolutionsHouseGfx : function() {
    //House graphic
    $("#house_gfx #industries a").mouseover(function() {
      var id     = $(this).attr("id");
      var overId = id + "_over";
      var overEl = $("#"+overId)
      overEl.removeClass("open");
      overEl.show();
    }).mouseout(function() {
      var id     = $(this).attr("id");
      var overId = id + "_over";
      var overEl = $("#"+overId);
      
      if(overEl.attr("over") == "Y") {
        overEl.addClass("open");
      } else {      
        overEl.hide();
      }
    });    
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Home Promos
  //////////////////////////////////////////////////////////////////////////////
  initHomePromos : function() {
    //Set the number of home promos for use later
    ispi.maxHomePromoIdx = $("#homePromoList").attr("maxHomePromoIdx");
    
    //Set the initial home promo dot as selected
    ispi.setHomePagePromoDot(ispi.currentHomePromoIdx);
    
    //Set the width of the home promo dots container in case we have > 3
    ispi.setHomePageDotsContainerWidth();
    
    //Start the home promo interval
    ispi.homePromoInterval = setInterval(ispi.nextHomePromo,
                                         ispi.homePromoIntervalMilliSeconds);
    
    //Make sure we don't keep running the home promo animation when the
    //window is not in focus
    if(/*@cc_on!@*/false) { // check for Internet Explorer
      document.onfocusin  = ispi.onWindowFocus;
      document.onfocusout = ispi.onWindowBlur;
    } else {
      window.onfocus = ispi.onWindowFocus;
      window.onblur  = ispi.onWindowBlur;
    }    
    
    //Left arrow click handler
    $("#leftArrow").click(function() {
      clearInterval(ispi.homePromoInterval);
      ispi.prevHomePromo();
    });
    
    //Right arrow click handler
    $("#rightArrow").click(function() {
      clearInterval(ispi.homePromoInterval);
      ispi.nextHomePromo();
    });
                
    //Click Handler for the dots
    $(".homePromoDot").click(function() {
      clearInterval(ispi.homePromoInterval);
      var idx = $(this).attr("homePromoIdx");
      if(idx > ispi.currentHomePromoIdx) {
        var slotsToMove = idx-ispi.currentHomePromoIdx;
        var prToMove    = slotsToMove * 100;
        $("#homePromoList").animate({"left": "-="+prToMove+"%"}, "fast");
        ispi.currentHomePromoIdx += slotsToMove;
      } else if(idx < ispi.currentHomePromoIdx) {
        var slotsToMove = ispi.currentHomePromoIdx - idx;
        var prToMove    = slotsToMove * 100;
        $("#homePromoList").animate({"left": "+="+prToMove+"%"}, "fast");
        ispi.currentHomePromoIdx -= slotsToMove;
      }
      
      ispi.setHomePagePromoDot(ispi.currentHomePromoIdx);
    });    
  },
  
  /* Slide the home promo list to the previous position. If we are at the
  start of the list of promos slide to the last one. */
  prevHomePromo: function() {    
    if(!ispi.homePromoActive) return;
    
    if(ispi.currentHomePromoIdx > 1) {
      $("#homePromoList").animate({"left": "+=100%"}, "fast");
      ispi.currentHomePromoIdx--;
      ispi.setHomePagePromoDot(ispi.currentHomePromoIdx);
    } else {
      var numSlotsToMove = ispi.maxHomePromoIdx-1;
      $("#homePromoList").animate({"left": "-="+(100*numSlotsToMove)+"%"}, "fast");
      ispi.currentHomePromoIdx += numSlotsToMove;
      ispi.setHomePagePromoDot(ispi.currentHomePromoIdx);
    }    
  },
  
  /* Slide the home promo list to the next position. If we are at the end of
  the list of promos slide to the first one. */
  nextHomePromo: function() {    
    if(!ispi.homePromoActive) return;
    
    if(ispi.currentHomePromoIdx < ispi.maxHomePromoIdx) {      
      $("#homePromoList").animate({"left": "-=100%"}, "fast");
      ispi.currentHomePromoIdx++;
      ispi.setHomePagePromoDot(ispi.currentHomePromoIdx);
    } else {
      var numSlotsToMove = ispi.maxHomePromoIdx-1;
      $("#homePromoList").animate({"left": "+="+(100*numSlotsToMove)+"%"}, "fast");
      ispi.currentHomePromoIdx -= numSlotsToMove;
      ispi.setHomePagePromoDot(ispi.currentHomePromoIdx);
    }    
  },
  
  /* Select the correct home promo dot when clicked. */
  setHomePagePromoDot: function(homePromoIdx) {
    $(".homePromoDot").removeClass("selectedHomePromoDot")
    $(".homePromoDot[homePromoIdx="+homePromoIdx+"]").addClass("selectedHomePromoDot");    
  },
  
  /* Make sure the width of the home promo dot container is
  wide enough to accomodate them. */
  setHomePageDotsContainerWidth: function() {
    var dotWidth = ispi.getElementWidth($(".homePromoDot"));
    $("#homePromoDots").css("width", $("#homePromoList").attr("maxHomePromoIdx")*dotWidth);    
  },
  
  /* Get the width of the passed element taking the CSS into account */
  getElementWidth: function(el) {
    var stripPx  = function(val) {
      try {
        var tVal = parseInt(val.replace("px",""));
        if(isNaN(tVal)) {
          return 0;
        } 
        return  tVal;
      } catch(e) {}
      return 0;
    }
    
    var cssAttrs = ["width", "margin-right", "margin-left",
                    "padding-right", "padding-left"];
    
    var width = 0;
    for(var a=0; a < cssAttrs.length; a++) {
      width += stripPx(el.css(cssAttrs[a]));
    }
    
    return width;
  },
  
  /* When the window is not in focus pause the home promo cycling. */
  onWindowBlur : function() {
    ispi.homePromoActive = false;    
  },
  
  /* When the window is in focus start the home promo cycling. */
  onWindowFocus : function() {
    ispi.homePromoActive = true;
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Logo Grid
  //////////////////////////////////////////////////////////////////////////////
  initLogoGrid : function() {
    //Start the logo grid interval
    ispi.logoGridInterval = setInterval(ispi.iterateOverLogoGrid,
                                        ispi.logoGridIntervalMilliSeconds);    
  },
  
  /* Iterate over the logo grid swapping them fading each set of icons
  out and then in again. */
  iterateOverLogoGrid : function() {
    //Save first element's info
    var src = $("#logoGridGroup img:first").attr("src");
    var alt = $("#logoGridGroup img:first").attr("alt");
    
    //Fade element out
    $("#logoGridGroup img:first").fadeOut("fast", function() {
      $(this).remove();
      $("#logoGridGroup").prepend($("<div id='tDiv' style='height:125px;'></div>"));
      $("#tDiv").slideUp("slow", function() {
        $(this).remove();
        $("#logoGridGroup").append($("<img src='"+src+"' alt='"+alt+"' style='display:none;' />"));
        $("#logoGridGroup img:last").fadeIn();
      })      
    });
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Menu
  //////////////////////////////////////////////////////////////////////////////
  initMenu : function() {
    //Set the initial background position for the menu
    ispi.initialMenuSpritePosition = $("#menu").css("background-position");
        
    //Add click handler to menu
    $("#menu>#menuItems>li").click(function() {
      ispi.selectMenuItem($(this));
    });   
    
    //Menu hover handlers
    $("#menu>#menuItems>li").hoverIntent(
      {
        over: function(){
          ispi.selectMenuItem($(this));        
        },
        timeout: 0,
        out: function() {
          $(".pages").stop(true, true).hide("fast"); //hide();
          ispi.currentMenuItemIdx = 0;      
        }
      }
    );
    
    //Hide the menu when scrolling
    $(window).scroll(function() {
      $(".pages").stop(true, true).hide();
    });    
  },
  
  /* Select a menu item and display it's drop down if applicable. */
  selectMenuItem: function(obj) {
    var selectedMenuItemIdx = obj.attr("selectedMenuItemIdx");
      
    if(selectedMenuItemIdx == undefined) {            
      if($(this).hasClass("pages")) {
        selectedMenuItemIdx = obj.parents("li").attr("selectedMenuItemIdx");
      }
    }
        
    if(selectedMenuItemIdx != ispi.currentMenuItemIdx) {        
      ispi.currentMenuItemIdx = selectedMenuItemIdx;      
      
      obj.children(".pages").clearQueue();      

      var menuItemOffset  = ((selectedMenuItemIdx-1)*ispi.menuSpriteOffset);
        
      //Hide all open sub menus
      $(".pages").stop(true, true).hide();
          
      //Make sure menu items are put back to base color
      $("#menu #menuItems li a").css("color", "#000");
            
      //Change the menu graphic to reflect the selected menu item
      $("#menu").css("background-position", "0px " + menuItemOffset + "px");
        
      //Change the selected menu item's text to white
      obj.children("a").css("color", "#FFF");
        
      //Show the correct sub-menu if this menu entry has a sub menu
      if(obj.children(".pages").length > 0) {
        obj.children(".pages").show("fast");
        obj.children(".pages").css("opacity", ".95");  
        ispi.positionDropDowns(); 
      }
         
      //Make sure the sub-menu text is white and not bold
      $(".pageLink").css("color","#FFF");
      $(".pageLink").css("font-weight","normal");
    }    
  },
  
  /* Position the menu drop downs. */
  positionDropDowns : function() {
    var obj = $("#menuItems li");
          var height       = parseInt(obj.css("height").replace("px",""));
          var menuPos      = obj.position().top;
          var scrollOffset = $(document).scrollTop();
          var dropDownPos  = menuPos - scrollOffset + height - ispi.dropDownHBuffer;
          
          obj.children(".pages").css("top", dropDownPos + "px");            
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Forms 
  //////////////////////////////////////////////////////////////////////////////
  initForms: function() {
    //Add handler to submit button for info request
    $("#infoRequestButton").click(function() {
      ispi.submitInformationRequest(document.info_form);
    });
    
    $("#pricingRequestButton").click(function() {
      ispi.submitPricingRequest(document.pricing_form);
    });
    
    //Pricing Request Drop Downs
    $("#pricingSolution").change(function() {
      var val = $(this).val();
      
      if(val == "enterprise_performance_management") {
        $("#dataManagement").hide();
        $("#performanceMangement").fadeIn("fast");
      } else {
        $("#performanceMangement").hide();
        $("#dataManagement").fadeIn("fast");
      }
    });    
  },
  
  /* Validate a form field using the passed function. If the
  field is empty then display the passed text in an alert(). */
  validateFormField : function(el, text, fun) {
    if(!fun){
      fun = function(el) { return true; }
    }
    
    if(el.value == "" || !fun(el)) {
      alert("Please enter a" + text);
      el.focus();
      return false;
    }
    return true;
  },
    
  /* Validate the submit pricing request form and submit it to the server. */
  submitPricingRequest : function(form) {
    if(ispi.validateFormField(form.company,          " company")                &&
       ispi.validateFormField(form.title,            " title")                  &&
       ispi.validateFormField(form.first_name,       " first name")             &&
       ispi.validateFormField(form.last_name,        " last name")              &&
       ispi.validateFormField(form.email,            "n email address")         &&
       ispi.validateFormField(form.phone,            " phone number")           &&
       ispi.validateFormField(form.pricing_solution, " solution for pricing")   &&
       ispi.validateFormField(form.project_start,    " start for this project")) {
        
      var combine = function(id) {
        var txt = "";
        $("#"+id+" input").each(function() {
          if($(this).attr("checked")) {
            txt += "- " + $(this).val() + "<br />";
          }
        });
        return txt;
      }
            
      form.performanceManagementActivities.value     = combine("performanceManagementActivities");
      form.performanceManagementGoals.value          = combine("performanceManagementGoals");
      form.dataManagementChallenges.value            = combine("dataManagementChallenges");
      form.preferredDataManagementTechnologies.value = combine("preferredDataManagementTechnologies");
      
      if($("#pricingSolution").val() == "enterprise_performance_management") {
        form.dataManagementImportance.disabled         = true;
        form.dataManagementEffectiveness.disabled      = true;
        form.dataManagementChallenges.value            = "";        
        form.preferredDataManagementTechnologies.value = "";
      } else {
        form.performanceManagementActivities.value                   = "";
        form.performanceManagementGoals.value                        = "";
        form.performanceManagementTheme.disabled                     = true;
        form.preferredPerformanceManagementTechnologyVendor.disabled = true;
      }      
      
      form.submit();
    }    
  },
  
  /* Validate the information request form to the server. */
  submitInformationRequest : function(form) {    
    if(ispi.validateFormField(form.company,    " company")        &&
       ispi.validateFormField(form.title,      " title")          &&
       ispi.validateFormField(form.first_name, " first name")     &&
       ispi.validateFormField(form.last_name,  " last name")      &&       
       ispi.validateFormField(form.email,      "n email address") &&
       ispi.validateFormField(form.phone,      " phone number")) {
      form.submit();
    }
  },
  
  //////////////////////////////////////////////////////////////////////////////
  // Home Page Folders
  //////////////////////////////////////////////////////////////////////////////
  initHomeFolders: function() {
    //Add click handler to home page folders
    $(".folderTitle").click(function() {
      var obj = $(this);
      ispi.selectHomeFolder(obj, obj.attr("folderIdx"));
    });      
  },
  
  /* Toggle the selected home folder. */
  selectHomeFolder: function(obj, folderIdx) {
    //Swap the folder background image position
    $("#folders").css("background-position",
                      "0px -"+((folderIdx-1)*ispi.homeFolderSpriteOffset)+"px");
    //Highlight the correct text
    $(".folderTitle").css("color", "#000");
    obj.css("color", "#FFF");
    //Hide all the content
    $(".folderContent").hide();
    //Show the correct content
    $(".folderContent[folderIdx="+folderIdx+"]").show();
  }
}

$(document).ready(function(){
  ispi.init();
});

