/****************************** Service Objects *******************************/

/* Container for an individual service */
var StrataFusionService = function(serviceId, flowText,
                                   wheelImage, stackImage,
                                   serviceLink) {
  this.serviceId   = serviceId;
  this.serviceLink = serviceLink;
  this.listId      = serviceId + "_list";
  this.flowId      = serviceId + "_flow";
  this.wheelId     = serviceId + "_wheel";
  this.stackId     = serviceId + "_stack";
  this.flowText    = flowText;
  this.wheelImage  = wheelImage;
  this.stackImage  = stackImage;
}

/* Holds a list of StrataFusionServices and all the methods necessary
to make use of them within the UI */
var StrataFusionServiceController = function() {
  var services     = [];
  var serviceIdxs  = [];
  var firstService = '';
  var serviceIdx   = -1; //Since we start with nothing selected. 0 is cio
  var numServices  = 0;
  var serviceLink  = '';
  var autoLoop     = '';

  /* Add a service to this instance of a ServiceController. */
  this.add = function(serviceId, flowText, wheelImage,
                      stackImage, serviceLink) {

    services[serviceId] = new StrataFusionService(serviceId, flowText,
                                                  wheelImage, stackImage,
                                                  serviceLink);

    if(numServices == 0) {
      firstService = services[serviceId];
    }
    
    serviceIdxs[serviceId] = numServices;

    numServices++;
  }
  
  /* Stop the auto rotating of services by clearing the interval of the
  service loop on the home page. */
  this.stopAutoRotate = function() {
    if(autoLoop) {
      clearInterval(autoLoop);
    }    
  }

  /* Change the home page to reflect the service
  identified by the passed serviceId. If initialToggle is false
  then we should stop auto looping through services. */
  this.toggle = function(serviceId, initialToggle) {
    //If a service is toggled then stop the service loop
    if(!initialToggle) {
      this.stopAutoRotate();
    }

    if(!serviceId) return;

    //Lookup Service
    var tService = services[serviceId];
    
    serviceIdx = serviceIdxs[serviceId];

    //Toggle Flow
    //Embedded HTML... Bad!!
    $('#flowText').html('DELIVERABLES: <span class="deliverableText">' +
                        tService.flowText + '</span>');
    $('.centerFlow').hide();
    $('#'+tService.flowId).show();
    serviceLink = tService.serviceLink;

    //Toggle List
    $('.homeServices ul').hide();
    $('#'+tService.listId).show();

    //Toggle Wheel
    swapImage('serviceWheel', tService.wheelImage, tService.flowText);

    //Toggle Stack
    swapImage('SpotlightImage', tService.stackImage, tService.flowText);
    
    //Toggle Service Dot
    $(".flowBarItem").css("background-color","#D0D0D0");
    $("#barItem_" + serviceId).css("background-color","#FF8633");    
  }
  
  /* Set the image and alt text for the given id. */
  var swapImage = function(id, img, txt) {
    $('#'+id).attr("src",img);
    $('#'+id).attr("alt",txt);
  }

  /* Redirect the browser to the selected service. */
  this.followServiceLink = function() {
    top.location = (serviceLink == '' ? firstService.serviceLink : serviceLink);
  }

  /* Select the next service in line cio -> hum */
  this.nextService = function() {
    if(serviceIdx >= numServices-1) {
      serviceIdx = 0;
    } else {
      serviceIdx++;
    }

    this.toggleByIdx(serviceIdx);
  }

  /* Select the last service in line hum -> cio */
  this.lastService = function() {

    if(serviceIdx <= 0) {
      serviceIdx = numServices-1;
    } else {
      serviceIdx--;
    }
    
    this.toggleByIdx(serviceIdx);
  }

  /* Set the id of the interval used for the timed loop on the home page. */
  this.setLoopId = function(id) {
    autoLoop = id;
  }
  
  /* Toggle the current service by the position it falls in
  the list cio/0, bi/1, trans/2, strat/3, hum/4 .*/
  this.toggleByIdx = function(serviceIdx) {
    var idx = 0;
    for(tServiceId in services) {
      if(idx == serviceIdx) {
        this.toggle(tServiceId, true);
        break;
      }
      idx++;
    }   
  }
}

/************************** Global Vars  **************************************/

var serviceController             = new StrataFusionServiceController();
var homePageServiceToggleInterval = 10; //seconds
//Alumni Image constants
var alumniImageToggleInterval     = 3;  //seconds
var maxAlumniIdx                  = 7;  //Max of 7 alumni images
//Current alumniIdx
var alumniIdx                     = 2;  //Start on the second alumni image
//URL to the success stories page
var successStoriesUrl             =  "/where-weve-delivered-our-solutions/success-stories/";

/********************************** On Load ***********************************/

$(document).ready(function() {

  //Add Services data to the controller
  serviceController.add('cio',
                        'CIO/CTO Advisory',
                        '/media/img/wheels/wheel1.png',
                        '/media/img/stacks/stack1.png',
                        '/cio-cto-advisory/');
  serviceController.add('bi',
                        'Business Intelligence',
                        '/media/img/wheels/wheel2.png',
                        '/media/img/stacks/stack2.png',
                        '/business-intelligence/');
  serviceController.add('trans',
                        'Cloud &amp; Transformative Technologies',
                        '/media/img/wheels/wheel3.png',
                        '/media/img/stacks/stack3.png',
                        '/cloud-and-transformative-technologies/');
  serviceController.add('strat',
                        'Strategic Sourcing',
                        '/media/img/wheels/wheel4.png',
                        '/media/img/stacks/stack4.png',
                        '/strategic-sourcing/');
  serviceController.add('hum',
                        'Human Capital</span>',
                        '/media/img/wheels/wheel5.png',
                        '/media/img/stacks/stack5.png',
                        '/human-capital/');

  //Add the top nav menu hover
  $(".topNavButton").hover(
    function() {
      var subMenu  = $(this).attr("subMenu");
      var buttonId = $(this).attr("button");
      //Make sure the "Tab" headers don't show through the menu
      $(".pageTab, .pageTabOver").css("z-index","1");
      $('#'+subMenu).show();
      
    },
    function() {
      var subMenu = $(this).attr("subMenu");
      var buttonId = $(this).attr("button");
      $(".pageTab").css("z-index",     "2");
      //Make sure the "Tab" headers are clickable when the menu is not open
      $(".pageTab, .pageTabOver").css("z-index","2");
      $('#'+subMenu).hide();
    }
  );

  //Add click handler for services list titles
  $('.homeServices h3').click(function() {
    serviceController.toggle($(this).attr("serviceId"));
  });

  //Add click handlers to service wheel
  $('.wshape, .stackmap').click(function() {
    //Deal with image map border on click w/Google Chrome
    $(this).blur();
    //Toggle Service
    serviceController.toggle($(this).attr("toggle"));
    serviceController.followServiceLink();
  });

  //Add click handler to search box
  $('#searchBox').click(function() {
    this.value = '';
  })

  // When the home page is loaded
  if(window.location.pathname == '/home/' ||
     window.location.pathname == '/') {

    //Add click handler for home page tab menus
    $(".homeMenu, .homeMenuOver").click(function() {
      var prefix = $(this).attr("id").replace("Item","");
      toggleHomeMenu(prefix);
    });

    //Add click handler to the home page tabs
    //i.e. Innovate, explore, community
    $(".pageTab, .pageTabOver").click(function() {
      var prefix = $(this).attr("id").replace("Tab","");
      toggleHomeTab(prefix);
    });

    //Add click handler to the home page sample deliverables
    $(".centerFlow").click(function() {
      serviceController.followServiceLink();
    });

    //Change services every 10 seconds until the service is toggled
    //via the service wheel
    serviceController.setLoopId(
      window.setInterval(
        function() {
          serviceController.nextService();
        },
        (homePageServiceToggleInterval*1000)
      )
    );
    
    //Add the click handler for the right scroll button on the flow area
    $("#flowScrollRight").click(function() {
      serviceController.nextService();
      serviceController.stopAutoRotate();
    });
    
    //Add the click handler for the left scroll button on the flow area
    $("#flowScrollLeft").click(function() {
      serviceController.lastService();
      serviceController.stopAutoRotate();
    });
    
    //Add the click handlers to each of the service indicators (grey/orange sq)
    //under the flow area
    $(".flowBarItem").click(function() {
      var sid = $(this).attr("serviceId");      
      serviceController.toggle(sid);      
    });

  } else { //Any page other than the home page

    //Set the service controller to "No services selected"
    serviceController.toggle('');

    //Fixes problem with ul padding spacing out bg image in page content box
    $(".pageContent ul:last").css("margin-bottom","0px");

    //Sync the heights for the page and the service
    syncHeights();

    //Add rotating alumni images to the culture/alumni page
    if($("#alumniImage").length > 0) {
      window.setInterval(
        function() {
          if(alumniIdx > maxAlumniIdx) {
            alumniIdx = 1;
          }

          $("#alumniImage").attr("src", "/media/assets/alumni"+
                                 alumniIdx+".png");
          alumniIdx++;
        },
        (alumniImageToggleInterval*1000)
      );
    }
    
    //Arrow Maps on the service pages
    //To enable an image to use this create an image map with an attribute "img"
    //that holds the base image. For each area tag set the class as "arrowMap"
    //and set the "img" attribute to the image to swap to.
    //
    //The starting image should have these attributes:
    //  id="serviceArrowImg"
    //  border="0"
    //  usemap="#mapName"
    if($("#serviceArrowImg").length > 0) {
      $(".arrowMap").mouseover(function() {
        var imageToSwap = $(this).attr("img");
        var flyoutId    = $(this).attr("flyout");
        $("#serviceArrowImg").attr("src", imageToSwap);
        var pos   = $("#serviceArrowImg").offset();  
        var width = $("#serviceArrowImg").width();
        $("#"+flyoutId).css( { "left": (pos.left + width) + "px",
                               "top" : (pos.top  + 55)    + "px" } );        
        $("#"+flyoutId).fadeIn();
      }).mouseout(function() {
        var baseImg = $(this).parent().attr("img");
        $("#serviceArrowImg").attr("src", baseImg);
        $(".flyout").fadeOut();
      });
    }

    //Load news RSS if applicable (News page only)
    if($("#newsRss").length > 0) {
      $.ajax({
        type: "GET",
        url:  "/news_rss/",
        data: "",
        success: function(resHtml) {
          $("#newsRss").html(resHtml);
          $(".pageContent").css("height","1500px");
          syncHeights();
        }
      });
    }
    
    //Add click handler(s) for success stories page
    if($(".successStories").length > 0) {
      $('.successMap, .successStoryHeader').click(function() {
        var toggle = $(this).attr("toggle");
        var ul     = $("#"+toggle+"_stories");
        serviceController.toggle(toggle);
        toggleSuccessStoryList(ul);
        window.location.hash = "#"+toggle;
      });
      
      //Read the hash tag out of the url
      var toggle = window.location.hash.replace("#","");
      if(toggle != "") {
        serviceController.toggle(toggle);
        toggleSuccessStoryList($("#"+toggle+"_stories"));
      }
    }
    
    //Re-route exploded cube to the success stories lander on
    //the business problem pages
    if((window.location.pathname+"").indexOf("/business-problem") == 0) {
      $("map area").each(function() {
        var toggle = $(this).attr("toggle");
        $(this).attr("href",successStoriesUrl+"#"+toggle);
      });
    }
  }
});

/***************** Success Story Specific Functions****************************/

var toggleSuccessStoryList = function(obj) {
  var imgIdx = obj.attr("imgIdx");
  $(".successStoryList").hide();
  obj.show();
  //Toggle Image
  $("#stackImage").attr("src", "/media/img/stacks/stack"+imgIdx+".png");
  
  /**** Start extras to deal with IE8 shenanigans ****/
  
  //Ensure li heights
  $(obj).children().each(function() {
    $(this).css("height",  "30px");
    $(this).css("padding", "0px");
    $(this).css("margin",  "0px");    
  });
  
  //Ensure ul height
  $(obj).css("height",      "90px");
  $(obj).css("margin",      "0px");
  $(obj).css("padding",     "0px");
  $(obj).css("margin-left", "30px");
  $(obj).css("list-style",  "square");
  
  //Ensure div heights
  $(".successStoryHeader").each(function() {
    $(this).css("height",        "20px");
    $(this).css("padding",       "0px");
    $(this).css("margin",        "0px");
    $(this).css("margin-bottom", "10px");
  });
  
  /**** End extras to deal with IE8 shenanigans ****/
}

/***************** Home Page Specific Functions *******************************/

var toggleHomeTab = function(prefix) {
  $(".pageTabOver").addClass('pageTab');
  $(".pageTabOver").removeClass('pageTabOver');
  $("#"+prefix+"Tab").addClass('pageTabOver');
  $(".homeTabContent").hide();
  $("#"+prefix+"Content").show();

  $("#"+prefix+"Content").find("li").each(function(i) {
    if(i==0) {
      $(this).click();
    }
  });
}

var toggleHomeMenu = function(prefix) {
  //Toggle Menu
  $(".homeMenuOver").addClass('homeMenu');
  $(".homeMenuOver").removeClass('homeMenuOver');
  $("#"+prefix+"Item").addClass('homeMenuOver');
  //Toggle Image
  $(".homeMenuImage").hide();
  $("#"+prefix+"Image").show();
  $("#"+prefix+"Image").css("display","inline");
  //Toggle Content
  $(".homeMenuContent").hide();
  $("#"+prefix+"Content").show();
}

var submitSurvey = function() {
  var selectedValue = $("input[name='survey_choice']:checked").val();
  if(selectedValue) {
    $.ajax({
      type: "POST",
      url:  "/survey/",
      data: "servicePrefix="+selectedValue,
      success: function(resHtml) {
        if(resHtml == 'success') {
          //Display Thank You Message
          $('#surveySubmitDiv').html("Thank you for participating");
          //Remove the button
          $('#surveySubmit').remove();
        }
      }
    });
  }
}

/************************* More Info Form *************************************/

var validPdf = function(pdf) {
  return downloadUrl == "CFO_Cloud_Sourcing_Assessment_And_IT_Outsourcing_Performance_Review.pdf"       ||
         downloadUrl == "CIO_Cloud_Sourcing_Assessment_And_IT_Outsourcing_Performance_Review_April.pdf" ||
         downloadUrl == "StrataFusion_LA_Dinner_Guests.pdf";
}

var submitInformationRequest = function() {

  var alertUser = function(text) {
    $('#infoSubmitDiv').html(text);
    scroll(0,0);
  }

  var downloadUrl   = location.hash;
  var title         = document.getElementById('title').value;
  var firstName     = document.getElementById('first_name').value;
  var lastName      = document.getElementById('last_name').value;
  var telephone     = document.getElementById('telephone').value;
  var company       = document.getElementById('company').value;
  var email         = document.getElementById('email').value;
  var comments      = document.getElementById('comments').value;
  var surveyResults = document.getElementById('survey_results').checked ? "Y" : "N";

  if(downloadUrl != "") {
    downloadUrl = downloadUrl.replace("#","");
  }

  if(!validPdf(downloadUrl)) {
    downloadUrl = "";
  }

  if(company == '') {
    alertUser('Please enter a company');
    $('#company').focus();
  } else if(title == '') {
    alertUser('Please enter a title');
    $('#title').focus();
  } else if(firstName == '') {
    alertUser('Please enter a first name');
    $('#first_name').focus();
  } else if(lastName == '') {
    alertUser('Please enter a last name');
    $('#last_name').focus();
  } else if(telephone == '') {
    alertUser('Please enter a telephone number');
    $('#telephone').focus();
  } else if(email == '') {
    alertUser('Please enter a valid email address');
    $('#email').focus();
  } else {
    $.ajax({
      type: "POST",
      url:  "/info-req/",
      data: "first_name="+firstName+
            "&last_name="+lastName+
            "&telephone="+telephone+
            "&company="+company+
            "&email="+email+
            "&comments="+comments+
            "&title="+title+
            "&survey_results="+surveyResults,
      success: function(resHtml) {
        if(resHtml == 'success') {
          //Display Thank You Message
          if(downloadUrl == '') {
            alertUser("Thank you for your request. " +
                      "A representative will contact you shortly.");
          } else {
            alertUser("Thank you, please click <a href='/media/pdf/"+
                      downloadUrl+"'>here</a> to download your document.");
          }
          //Rem Button
          $('#infoSubmit').fadeOut();
        }
      }
    });
  }
}

var syncHeights = function() {
  //Sync the height of the services area and the main content area
  var pHeight = $(".pageContent").height();
  var sHeight = $(".serviceContent").height();
  var margin  = 11; //px buffer

  if(pHeight > sHeight) {
    var diff = pHeight - sHeight;
    $(".serviceContent").css("height",(diff+sHeight-margin)+"px");
  } else {
    $(".pageContent").css("height",(sHeight+margin)+"px");
  }
}

