/*
 * Common JS
 * @author Engineering
 * @fileoverview
 * 
 * Javascript for common project components 
 *
 */

var COMMON_globalConstants = {
  current: 'current',
  currentFirstChild: 'currentFirstChild',
  currentLastChild: 'currentLastChild', 
  currentNext: 'currentNext',
  currentPrev: 'currentPrev',
  firstChild: 'firstChild',
  IE6Hover: 'IE6Hover',
  lastChild: 'lastChild',
  mouseoverImageSuffix: '_on',
  mouseoutImageSuffix: '_off'
};
  
/*
 * accordion component code
 * @class COMMON_accordion
 */
var COMMON_accordion = function () {
  var classes = {
    clicked: 'clicked'
  };
  
  return {
    init: function () {
      COMMON_accordion.addClasses();
      COMMON_accordion.bindAccordionLinks();                            
    },
    /*
     * adds classes to first and last li child of tabLinks ul in each tabsComponent for styling purposes
     * 
     * What it does:
     *    adds class defined in COMMON_globalConstants variables to each tabLinks list first child and last child 
     * 
     */           
    addClasses: function () {
      // extra tab class hooks for styling, etc.
      $('div.accordionComponent').each (function () {
        var thisAccordionComponent = $(this);
    
        thisAccordionComponent.find('ul.accordionItems li:first').addClass(COMMON_globalConstants.firstChild);
        thisAccordionComponent.find('ul.accordionItems li:last').addClass(COMMON_globalConstants.lastChild);  
      });
    },
    /*
     * sets up behaviors to run when the tab links are clicked
     * 
     * What it does:
     *    gathers all accordionComponent divs on the page. For each, gather all the a tags and bind with an onclick handler. Whenever a link is clicked,
     *    remove all 'current', 'currentNext' and/or 'currentPrev' classes from all the accordion links. Retrieve and add 'current'
     *    to the list item parent of the tab link which was clicked and also add 'currentNext'/'currentPrev' classes to the next/previous siblings (if they exist.)
     * 
     */     
    bindAccordionLinks: function () {
      // for each accordionComponent on the page
      $('div.accordionComponent').each (function () {
        var thisAccordionComponent = $(this);
        var accordionLinks = thisAccordionComponent.find('ul.accordionItems > li a.tabLink');
        // bind accordion link clicks to showing correct tab content
        accordionLinks.bind('click', function (e) {
          var accordionLink = $(this);              
          var e = e || window.event;
          e.preventDefault(); 
          
          // remove these classes from everything but the clicked link
          accordionLinks.each(function () {
            var li = $(this).not(accordionLink).parents('li');
            li.removeClass(COMMON_globalConstants.current);
            li.removeClass(COMMON_globalConstants.currentPrev);
            li.removeClass(COMMON_globalConstants.currentNext);
          });
                    
          // add 'current' to the list item for the link just clicked
          accordionLink.parents('li').toggleClass(COMMON_globalConstants.current);                    
          // add 'currentPrev' to the sibling of the list item for the link just clicked
          accordionLink.parents('li').prev().toggleClass(COMMON_globalConstants.currentPrev);         
          // add 'currentNext' to the sibling of the list item for the link just clicked
          accordionLink.parents('li').next().toggleClass(COMMON_globalConstants.currentNext);           
  
        });
      });     
    }
  }
}();

 
/*
 * breadcrumb code
 * @class COMMON_breadcrumb
 */
var COMMON_breadcrumb = function () { 
  return {
    init: function () {
      COMMON_breadcrumb.addClasses();
    },
    /*
     * adds classes to first and last li child of breadcrumb ul in each breadcrumb for styling purposes
     * 
     * What it does:
     *    adds class defined in COMMON_globalConstants variable to each breadcrumb list first child and last child
     * 
     */           
    addClasses: function () {
      // extra tab class hooks for styling, etc.
      $('div.breadcrumb').each (function () {
        var thisTabsComponent = $(this);
    
        thisTabsComponent.find('ul li:first').addClass(COMMON_globalConstants.firstChild);
        thisTabsComponent.find('ul li:last').addClass(COMMON_globalConstants.lastChild);    
      });
    }
  };
}(); 
 
 
/*
 * content pager code
 * @class COMMON_contentPager
 */ 
var COMMON_contentPager = function () {
  return {
    init: function () {   
      COMMON_contentPager.bindMouseEvents();    
      COMMON_contentPager.addClasses();     
    },
    /*
     * adds classes to first and last li child of content pager control progress indicator in each content pager for styling purposes
     * 
     * What it does:
     *    adds class defined in COMMON_globalConstants variable to each progress indicator list first child and last child
     * 
     */               
    addClasses: function () {
      $('div.contentPager').each(function () {
        var thisContentPager = $(this);   
        thisContentPager.find('ul.contentPagerControl li ul li:first').addClass(COMMON_globalConstants.firstChild);   
        thisContentPager.find('ul.contentPagerControl li ul li:last').addClass(COMMON_globalConstants.lastChild);   
        thisContentPager.find('li.progressIndicator ul li:first').addClass(COMMON_globalConstants.current);
      });
    },
    /*
     * sets up behaviors to run when the content pager links are clicked
     * 
     * What it does:
     *    gathers all contentPager divs on the page. For each, gather all the previous page links and bind with an onclick handler. Whenever a previous link is clicked,
     *    find the content page with the 'current' link and add 'current' class to the previous content page. If that is successful, remove the 'current' class from the 
     *    one that was previously current. if the progress indicator links are being shown, update the controls. Do something similar for the next page link. For the 
     *    progress indicator links, when a link is clicked, remove 'current' class from all content pages and then, based on the index of the control link clicked, 
     *    select the corresponding content div and add the 'current' class.
     * 
     */         
    bindMouseEvents: function () {
      $('div.contentPager').each(function () {
        var thisContentPager = $(this);
        var progressIndicatorLinks = thisContentPager.find('li.progressIndicator a');       
        
        thisContentPager.find('li.prevPage a').bind('click', function (e) {   
          var e = e || window.event;
          e.preventDefault();
          
          /* todo: get correct tracking stuff 
          COMMON_tracking.triggerTracking('Navigation: Previous > Click ', 'UOPX: Home > Highlights');
          */
          var currentPage = thisContentPager.find('div.pagerContentContainer div.current');         
          var result = currentPage.prev().addClass(COMMON_globalConstants.current); 
          if (result.length) {
            currentPage.removeClass(COMMON_globalConstants.current);
            if (thisContentPager.find('li.progressIndicator').length) {           
              COMMON_contentPager.updateControls(thisContentPager, progressIndicatorLinks, 'prev');
            }
          }
        });

        thisContentPager.find('li.nextPage a').bind('click', function (e) {
          var e = e || window.event;
          e.preventDefault();
        
          /* todo: get correct tracking stuff 
          COMMON_tracking.triggerTracking('Navigation: Previous > Click ', 'UOPX: Home > Highlights');
          */
          var currentPage = thisContentPager.find('div.pagerContentContainer div.current');                 
          var result = currentPage.next().addClass(COMMON_globalConstants.current);         
          if (result.length) {
            currentPage.removeClass(COMMON_globalConstants.current);
            if (thisContentPager.find('li.progressIndicator').length) {
              COMMON_contentPager.updateControls(thisContentPager, progressIndicatorLinks, 'next');
            }
          }
        });
        
        progressIndicatorLinks.bind('click', function (e) {
          var e = e || window.event;
          e.preventDefault();
  
          /* todo: get correct tracking stuff 
          COMMON_tracking.triggerTracking('Navigation: Previous > Click ', 'UOPX: Home > Highlights');
          */
          // get the index of the link that was clicked
          var linkIndex = progressIndicatorLinks.index(this); 
          // remove 'current' from all content pages
          thisContentPager.find('div.pagerContentContainer div.pagerContent').removeClass(COMMON_globalConstants.current);
          // remove 'current' from all control list items
          progressIndicatorLinks.each(function () {
            $(this).parent('li').removeClass(COMMON_globalConstants.current);
          });
          // add 'current' to the list item parent of the clicked link
          $(this).parent('li').addClass(COMMON_globalConstants.current);
          // add 'current to the content page that corresponds to the index of the tab link clicked 
          $(thisContentPager.find('div.pagerContentContainer div.pagerContent').get(linkIndex)).addClass(COMMON_globalConstants.current);
        });
                
      });
    },
    /*
     * update progress indicator links when stepping via next/prev page links
     * 
     * What it does:
     *    remove the 'current' class from all control list items. find the index of the page marked as current; using this index, get the corresponding
     *    progress control link and add the 'current' class to its list item.
     * 
     */             
    updateControls: function (thisContentPager, progressIndicatorLinks, direction) {
      progressIndicatorLinks.each(function () {
        $(this).parent('li').removeClass(COMMON_globalConstants.current);
      });       
    
      var currentPageIndex = thisContentPager.find('div.pagerContentContainer div.pagerContent').index(thisContentPager.find('div.pagerContentContainer div.current')); 
      $(progressIndicatorLinks.get(currentPageIndex)).parent('li').addClass(COMMON_globalConstants.current);    
    }   
  }
}(); 
 
/*
 * image mouseover code
 * @class COMMON_imageMouseover
 */ 
 
var COMMON_imageMouseover = function () {
  var constants = {
    mouseoverClass: 'mouseover'
  };

  return {
    init: function () {
      COMMON_imageMouseover.bindMouseEvents();
    },
    /*
     * adds mouseover/mouseout events to images for rollover states
     * 
     * What it does:
     *    gathers all images on the page. for mouseovers: if the image has '_off.' in the image path, replace '_off' with '_on' and add a class to the image to indicate a mouseover
     *    was triggered (to differentiate when mousing over/out of images that don't have rollover states.) for mouseouts: if the image has '_on.' in the image path AND has the 
     *    mouseover trigger class, replace '_on' with off and remove the class.
     * 
     */     
    bindMouseEvents: function () {
      $('img, input[type=image]').each(function () {
        $(this).bind('mouseover', function () {
          var src = $(this).attr('src');
          var regexp = new RegExp(COMMON_globalConstants.mouseoutImageSuffix, 'g');

          if (src.search(regexp) > -1) {
            $(this).attr('src', src.replace(regexp, COMMON_globalConstants.mouseoverImageSuffix));
            // add class as indicator mouseover activated
            $(this).addClass(constants.mouseoverClass);
          }
        });

        $(this).bind('mouseout', function () {            
          var src = $(this).attr('src');
          var regexp = new RegExp(COMMON_globalConstants.mouseoverImageSuffix, 'g');

          if (src.search(regexp) > -1 && $(this).hasClass(constants.mouseoverClass)) {                
            $(this).attr('src', src.replace(regexp, COMMON_globalConstants.mouseoutImageSuffix));
            $(this).removeClass(constants.mouseoverClass);
          }
        });
      });     
    }
  };
}();

 
/*
 * table code
 * @class COMMON_table
 */
var COMMON_table = function () {
  var classes = {
    rowStyle: 'altRow'
  };
  
  return {
    init: function () {
      COMMON_table.addClasses();
      COMMON_table.stripeRows();
    },
    addClasses: function () {
      $('table').each(function () {
        var thisTable = $(this);
        
        thisTable.find('tr:first').addClass(COMMON_globalConstants.firstChild);
        thisTable.find('tr:last').addClass(COMMON_globalConstants.lastChild);       
      });
      
      $('tr').each(function () {
        var thisRow = $(this);
      

        thisRow.find('td:first').addClass(COMMON_globalConstants.firstChild);
        thisRow.find('td:last').addClass(COMMON_globalConstants.lastChild); 
        
        thisRow.find('th:first').addClass(COMMON_globalConstants.firstChild);
        thisRow.find('th:last').addClass(COMMON_globalConstants.lastChild);     
      });
    },
    /*
     * adds a class to every other row of all tables for styling purposes
     * 
     * What it does:
     *    adds class defined in rowStyle variable to all even rows in page tables
     * 
     */       
    stripeRows: function () {
      $('table').find('tr:even').addClass(classes.rowStyle);
    }
  };
}();


/*
 * tabs_display component code
 * @class COMMON_tabs_display
 */
var COMMON_tabs_display = function () {
  var classes = {
    tabClass_close: 'close',
    tabClass_expand: 'expand',
    tabClass_link: 'link',
    tabClass_tab: 'tab'     
  };

  return {
    init: function () {
      COMMON_tabs_display.addClasses();
      COMMON_tabs_display.bindTabLinks();   
    },
    /*
     * adds classes to first and last li child of tabLinks ul in each tabsComponent for styling purposes
     * 
     * What it does:
     *    adds class defined in COMMON_globalConstants variables to each tabLinks list first child and last child 
     * 
     */           
    addClasses: function () {
      // extra tab class hooks for styling, etc.
      $('div.tabsComponent').each (function () {
        var thisTabsComponent = $(this);
    
        thisTabsComponent.find('ul.tabLinks li:first').addClass(COMMON_globalConstants.firstChild);
        thisTabsComponent.find('ul.tabLinks li:last').addClass(COMMON_globalConstants.lastChild); 

        // if the first content tab is already being displayed (ie, has class 'current'), add 'currentFirstChild' for stupid ie6, which doesn't support chained classes
        if (thisTabsComponent.find('div.tabContentContainer div.tabContent:first').hasClass(COMMON_globalConstants.current)) {
          thisTabsComponent.find('ul.tabLinks li:first').addClass(COMMON_globalConstants.current);
          thisTabsComponent.find('ul.tabLinks li:first').addClass(COMMON_globalConstants.currentFirstChild);
          thisTabsComponent.find('ul.tabLinks li:first').next().addClass(COMMON_globalConstants.currentNext);       
        }
      });
    },
    /*
     * sets up behaviors to run when the tab links are clicked
     * 
     * What it does:
     *    gathers all tabsComponent divs on the page. For each, gather all the a tags and bind with an onclick handler. Whenever a link is clicked,
     *    remove all 'current', 'currentNext' and/or 'currentPrev' classes from all the tabLinks list items and content tabs. Retrieve and add 'current'
     *    to the list item parent of the tab link which was clicked and also add 'currentNext'/'currentPrev' classes to the next/previous siblings (if they exist.)
     *    Based on the index of the tab link clicked, select the corresponding content div and add the 'current' class to that as well.
     * 
     */     
    bindTabLinks: function () {
      // for each tabsComponent on the page
      $('div.tabsComponent').each (function () {
        var thisTabsComponent = $(this);
        var tabLinks = thisTabsComponent.find('ul.tabLinks li a.tabLink');
        // bind tab link clicks to showing correct tab content
        tabLinks.bind('click', function (e) {
          var tabLink = $(this);              
          var e = e || window.event;
                
          // don't do any of this class switching if we're clicking on a link tab, since we're just going to a new page anyway
          if (!tabLink.hasClass(classes.tabClass_link)) {
            e.preventDefault(); 
            
            // get the index of the tab that was clicked
            var tabIndex = tabLinks.index(this);  
          
            // remove 'current' from all tab list items
            thisTabsComponent.find('ul.tabLinks li').removeClass(COMMON_globalConstants.current);
            thisTabsComponent.find('ul.tabLinks li:first').removeClass(COMMON_globalConstants.currentFirstChild);
            thisTabsComponent.find('ul.tabLinks li:last').removeClass(COMMON_globalConstants.currentLastChild);
            // remove 'currentPrevious' and 'currentNext' from all tab list items
            thisTabsComponent.find('ul.tabLinks li').removeClass(COMMON_globalConstants.currentPrev);
            thisTabsComponent.find('ul.tabLinks li').removeClass(COMMON_globalConstants.currentNext);         
          
          
            // add 'current' to the list item for the link just clicked
            tabLink.parents('li').addClass(COMMON_globalConstants.current);
            // add 'currentFirstChild' for stupid ie6, which doesn't support chained classes
            if (tabLink.parents('li').hasClass(COMMON_globalConstants.firstChild)) {
              tabLink.parents('li').addClass(COMMON_globalConstants.currentFirstChild);
            }
            // add 'currentLastChild' for stupid ie6, which doesn't support chained classes
            if (tabLink.parents('li').hasClass(COMMON_globalConstants.lastChild)) {
              tabLink.parents('li').addClass(COMMON_globalConstants.currentLastChild);
            }
            
            // add 'currentPrev' to the sibling of the list item for the link just clicked
            tabLink.parents('li').prev().addClass(COMMON_globalConstants.currentPrev);          
            // add 'currentNext' to the sibling of the list item for the link just clicked
            tabLink.parents('li').next().addClass(COMMON_globalConstants.currentNext);

            // remove 'current' from all content tabs
            thisTabsComponent.find('div.tabContentContainer div.tabContent').removeClass(COMMON_globalConstants.current);
            // add 'current to the content tab that corresponds to the index of the tab link clicked 
            $(thisTabsComponent.find('div.tabContentContainer div.tabContent').get(tabIndex)).addClass(COMMON_globalConstants.current);
            
            tabLinks.each(function () {
              if ($(this).hasClass(classes.tabClass_close)) {
                $(this).removeClass(classes.tabClass_close);
                $(this).addClass(classes.tabClass_expand);
              }
            });
            
            if (tabLink.hasClass(classes.tabClass_expand)) {
              tabLink.removeClass(classes.tabClass_expand);
              tabLink.addClass(classes.tabClass_close);
            }         
          } 
        });
      });     
    }
  }
}();


var COMMON_tracking = function () {
  return  {
    init: function () {
    
    },
    trackingRedirect: function (url, trackingId, trackingGroup) {
      cmCreatePageElementTag(trackingId, trackingGroup);
      
      var passedUrl = url;
      //Check if the url starts with "http://" or not
      if(passedUrl.match('^http://') == 'http://'){
        passedUrl = passedUrl.substring(passedUrl.indexOf('/', 7));
      }
      cmCreateManualLinkClickTag(passedUrl, 'Features');
      
      //Redirect to the url
      window.location = url;      
    },
    triggerTracking: function (trackingId, trackingGroup) {
      cmCreatePageElementTag(trackingId, trackingGroup);    
    } 
  }
}();


/* AudioPlayer Component */

// An array for all audioplayer swf names.
var audioPlayerArray = [];

function newAudioplayer(track, divId) {
  // Uses divId as unique identifier:
  var playerIDString = divId;
  // Push unique name into array:
  audioPlayerArray[audioPlayerArray.length] = divId;
  //variables used by audioplayer:
  var flashvars = {playerID: playerIDString, soundFile: track};
  //standard flash player params:
  var params = {menu: "false", wmode: "transparent", quality: "high", bgcolor: "#FFFFFF", allowFullScreen: "false", allowScriptAccess: "always", base: ""};
  //embed swf with SWFObject:
  swfobject.embedSWF("/etc/designs/common/swf/audioplayer/player.swf", playerIDString, "290", "24", "9.0.0", null, flashvars, params);
}

//Global function. ap_stopAll stops audio from playing in all audioplayers except the one that was just clicked.
function ap_stopAll(player) {
    console.log("ap_stopAll() player : " + player);
  //'player' is a reference to the SWF clicked.
  for(var i = 0; i < audioPlayerArray.length; i++) {
    //Loop through all audioplayers. 'swf' is each one:
    var swf = swfobject.getObjectById(audioPlayerArray[i]);
    try {
      // if each swf is not 'player' swf, pause and close it:
      if(swf != player) {
        console.log("if swf != player -- swf : " + swf);
        console.log("if swf != player -- player : " + player);
        swf.SetVariable("closePlayer", 1);
      }
      // otherwise leave it open.
      else {
        console.log("if swf == player -- swf : " + swf);
        console.log("if swf == player -- player : " + player);
        swf.SetVariable("closePlayer", 0);
      }
    //trace problems in Firebug Console:
    } catch( errorObject ) {
      console.log("ERROR STOPPING PLAYERS : " + errorObject);
    }
  }
}

function constructColCtrlLayout(dialog, value) {
  var layoutCls = value + ";cq-colctrl-default";
  var params = {};
  params['./layout'] = layoutCls;
  dialog.addHidden(params); 
}


/*
 * this function is called from dialog.xml files to change the storage path
 * 
 * What it does:
 *    replaces the dialog.loadContent function with one that changes the content path; then it executes
 *    the original function.
 * 
 */         
function setDialogStorePath(obj, strPath)
{
  var dlgParent=obj.findParentByType('dialog');
  dlgParent.tmpLoad = dlgParent.loadContent;
  dlgParent.loadContent = function(content) {
      dlgParent.content=strPath;
      dlgParent.tmpLoad(dlgParent.content);
  } 
}
