/*

 * jQuery clueTip plugin

 * Version 0.9.8  (05/22/2008)

 * @requires jQuery v1.1.4+

 * @requires Dimensions plugin (for jQuery versions < 1.2.5)

 *

 * Dual licensed under the MIT and GPL licenses:

 * http://www.opensource.org/licenses/mit-license.php

 * http://www.gnu.org/licenses/gpl.html

 *

 */

(function($) {

/*

 * @name clueTip

 * @type jQuery

 * @cat Plugins/tooltip

 * @return jQuery

 * @author Karl Swedberg

 *

 * @credit Inspired by Cody Lindley's jTip (http://www.codylindley.com)

 * @credit Thanks to the following people for their many and varied contributions:

      Shelane Enos, Glen Lipka, Hector Santos, Torben Schreiter, Dan G. Switzer, Jörn Zaefferer 

 * @credit Thanks to Jonathan Chaffer, as always, for help with the hard parts. :-)

 */



 /**

 * 

 * Displays a highly customizable tooltip when the user hovers (default) or clicks (optional) the matched element. 

 * By default, the clueTip plugin loads a page indicated by the "rel" attribute via ajax and displays its contents.

 * If a "title" attribute is specified, its value is used as the clueTip's heading.

 * The attribute to be used for both the body and the heading of the clueTip is user-configurable. 

 * Optionally, the clueTip's body can display content from an element on the same page.

 * * Just indicate the element's id (e.g. "#some-id") in the rel attribute.

 * Optionally, the clueTip's body can display content from the title attribute, when a delimiter is indicated. 

 * * The string before the first instance of the delimiter is set as the clueTip's heading.

 * * All subsequent strings are wrapped in separate DIVs and placed in the clueTip's body.

 * The clueTip plugin allows for many, many more options. Pleasee see the examples and the option descriptions below...

 * 

 * 

 * @example $('#tip).cluetip();

 * @desc This is the most basic clueTip. It displays a 275px-wide clueTip on mouseover of the element with an ID of "tip." On mouseout of the element, the clueTip is hidden.

 *

 *

 * @example $('a.clue').cluetip({

 *  hoverClass: 'highlight',

 *  sticky: true,

 *  closePosition: 'bottom',

 *  closeText: '<img src="cross.png" alt="close" />',

 *  truncate: 60,

 *  ajaxSettings: {

 *    type: 'POST'

 *  }

 * });

 * @desc Displays a clueTip on mouseover of all <a> elements with class="clue". The hovered element gets a class of "highlight" added to it (so that it can be styled appropriately. This is esp. useful for non-anchor elements.). The clueTip is "sticky," which means that it will not be hidden until the user either clicks on its "close" text/graphic or displays another clueTip. The "close" text/graphic is set to diplay at the bottom of the clueTip (default is top) and display an image rather than the default "Close" text. Moreover, the body of the clueTip is truncated to the first 60 characters, which are followed by an ellipsis (...). Finally, the clueTip retrieves the content using POST rather than the $.ajax method's default "GET."

 * 

 * More examples can be found at http://plugins.learningjquery.com/cluetip/demo/

 * 

 * Full list of options/settings can be found at the bottom of this file and at http://plugins.learningjquery.com/cluetip/

 */



  var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $dropShadow, imgCount;

  $.fn.cluetip = function(js, options) {

    if (typeof js == 'object') {

      options = js;

      js = null;

    }

    return this.each(function(index) {

      var $this = $(this);      

      

      // support metadata plugin (v1.0 and 2.0)

      var opts = $.extend(false, {}, $.fn.cluetip.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});



      // start out with no contents (for ajax activation)

      var cluetipContents = false;

      var cluezIndex = parseInt(opts.cluezIndex, 10)-1;

      var isActive = false, closeOnDelay = 0;



      // create the cluetip divs

      if (!$('#cluetip').length) {

        $cluetipInner = $('<div id="cluetip-inner"></div>');

        $cluetipTitle = $('<h3 id="cluetip-title"></h3>');        

        $cluetipOuter = $('<div id="cluetip-outer"></div>').append($cluetipInner).prepend($cluetipTitle);

        $cluetip = $('<div id="cluetip"></div>').css({zIndex: opts.cluezIndex})

        .append($cluetipOuter).append('<div id="cluetip-extra"></div>')[insertionType](insertionElement).hide();

        $('<div id="cluetip-waitimage"></div>').css({position: 'absolute', zIndex: cluezIndex-1})

        .insertBefore('#cluetip').hide();

        $cluetip.css({position: 'absolute', zIndex: cluezIndex});

        $cluetipOuter.css({position: 'relative', zIndex: cluezIndex+1});

        $cluetipArrows = $('<div id="cluetip-arrows" class="cluetip-arrows"></div>').css({zIndex: cluezIndex+1}).appendTo('#cluetip');

      }

      var dropShadowSteps = (opts.dropShadow) ? +opts.dropShadowSteps : 0;

      if (!$dropShadow) {

        $dropShadow = $([]);

        for (var i=0; i < dropShadowSteps; i++) {

          $dropShadow = $dropShadow.add($('<div></div>').css({zIndex: cluezIndex-i-1, opacity:.1, top: 1+i, left: 1+i}));

        };

        $dropShadow.css({position: 'absolute', backgroundColor: '#000'})

        .prependTo($cluetip);

      }

      var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass;

      if (!tipAttribute && !opts.splitTitle && !js) return true;

      // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip      

      if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); }

      var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10);

      // vertical measurement variables

      var tipHeight, wHeight;

      var defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px';

      var sTop, linkTop, posY, tipY, mouseY, baseline;

      // horizontal measurement variables

      var tipInnerWidth = isNaN(parseInt(opts.width, 10)) ? 275 : parseInt(opts.width, 10);

      var tipWidth = tipInnerWidth + (parseInt($cluetip.css('paddingLeft'))||0) + (parseInt($cluetip.css('paddingRight'))||0) + dropShadowSteps;

      var linkWidth = this.offsetWidth;

      var linkLeft, posX, tipX, mouseX, winWidth;

            

      // parse the title

      var tipParts;

      var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : '';

      if (opts.splitTitle) {

        if(tipTitle == undefined) {tipTitle = '';}

        tipParts = tipTitle.split(opts.splitTitle);

        tipTitle = tipParts.shift();

      }

      var localContent;



/***************************************      

* ACTIVATION

****************************************/

    

//activate clueTip

    var activate = function(event) {

      if (!opts.onActivate($this)) {

        return false;

      }

      isActive = true;

      $cluetip.removeClass().css({width: tipInnerWidth});

      if (tipAttribute == $this.attr('href')) {

        $this.css('cursor', opts.cursor);

      }

      $this.attr('title','');

      if (opts.hoverClass) {

        $this.addClass(opts.hoverClass);

      }

      linkTop = posY = $this.offset().top;

      linkLeft = $this.offset().left;

      mouseX = event.pageX;

      mouseY = event.pageY;

      if ($this[0].tagName.toLowerCase() != 'area') {

        sTop = $(document).scrollTop();

        winWidth = $(window).width();

      }

// position clueTip horizontally

      if (opts.positionBy == 'fixed') {

        posX = linkWidth + linkLeft + lOffset;

        $cluetip.css({left: posX});

      } else {

        posX = (linkWidth > linkLeft && linkLeft > tipWidth)

          || linkLeft + linkWidth + tipWidth + lOffset > winWidth 

          ? linkLeft - tipWidth - lOffset 

          : linkWidth + linkLeft + lOffset;

        if ($this[0].tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse

          if (mouseX + 20 + tipWidth > winWidth) {  

            $cluetip.addClass(' cluetip-' + ctClass);

            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'),10) + parseInt($cluetipInner.css('marginRight'),10) :  mouseX - (tipWidth/2);

          } else {

            posX = mouseX + lOffset;

          }

        }

        var pY = posX < 0 ? event.pageY + tOffset : event.pageY;

        $cluetip.css({left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0)});

      }

        wHeight = $(window).height();



/***************************************

* load a string from cluetip method's first argument

***************************************/

      if (js) {

        $cluetipInner.html(js);

        cluetipShow(pY);

      }

/***************************************

* load the title attribute only (or user-selected attribute). 

* clueTip title is the string before the first delimiter

* subsequent delimiters place clueTip body text on separate lines

***************************************/



      else if (tipParts) {

        var tpl = tipParts.length;

        for (var i=0; i < tpl; i++){

          if (i == 0) {

            $cluetipInner.html(tipParts[i]);

          } else { 

            $cluetipInner.append('<div class="split-body">' + tipParts[i] + '</div>');

          }            

        };

        cluetipShow(pY);

      }

/***************************************

* load external file via ajax          

***************************************/



      else if (!opts.local && tipAttribute.indexOf('#') != 0) {

        if (cluetipContents && opts.ajaxCache) {

          $cluetipInner.html(cluetipContents);

          cluetipShow(pY);

        }

        else {

          var ajaxSettings = opts.ajaxSettings;

          ajaxSettings.url = tipAttribute;

          ajaxSettings.beforeSend = function() {

            $cluetipOuter.children().empty();

            if (opts.waitImage) {

              $('#cluetip-waitimage')

              .css({top: mouseY+20, left: mouseX+20})

              .show();

            }

          };

         ajaxSettings.error = function() {

            if (isActive) {

              $cluetipInner.html('<i>sorry, the contents could not be loaded</i>');

            }

          };

          ajaxSettings.success = function(data) {

            cluetipContents = opts.ajaxProcess(data);

            if (isActive) {

              $cluetipInner.html(cluetipContents);

            }

          };

          ajaxSettings.complete = function() {

          	imgCount = $('#cluetip-inner img').length;

        		if (imgCount && !$.browser.opera) {

        		  $('#cluetip-inner img').load(function() {

          			imgCount--;

          			if (imgCount<1) {

          				$('#cluetip-waitimage').hide();

          			  if (isActive) cluetipShow(pY);

          			}

        		  }); 

        		} else {

      				$('#cluetip-waitimage').hide();

        		  if (isActive) cluetipShow(pY);    

        		} 

          };

          $.ajax(ajaxSettings);

        }



/***************************************

* load an element from the same page

***************************************/

      } else if (opts.local){

        var $localContent = $(tipAttribute + ':first');

        var localCluetip = $.fn.wrapInner ? $localContent.wrapInner('<div></div>').children().clone(true) : $localContent.html();

        $.fn.wrapInner ? $cluetipInner.empty().append(localCluetip) : $cluetipInner.html(localCluetip);

        cluetipShow(pY);

      }

    };



// get dimensions and options for cluetip and prepare it to be shown

    var cluetipShow = function(bpY) {

      $cluetip.addClass('cluetip-' + ctClass);

      

      if (opts.truncate) { 

        var $truncloaded = $cluetipInner.text().slice(0,opts.truncate) + '...';

        $cluetipInner.html($truncloaded);

      }

      function doNothing() {}; //empty function

      tipTitle ? $cluetipTitle.show().html(tipTitle) : (opts.showTitle) ? $cluetipTitle.show().html('&nbsp;') : $cluetipTitle.hide();

      if (opts.sticky) {

        var $closeLink = $('<div id="cluetip-close"><a href="#">' + opts.closeText + '</a></div>');

        (opts.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (opts.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner);

        $closeLink.click(function() {

          cluetipClose();

          return false;

        });

        if (opts.mouseOutClose) {

          if ($.fn.hoverIntent && opts.hoverIntent) { 

            $cluetip.hoverIntent({

              over: doNothing, 

              timeout: opts.hoverIntent.timeout,  

              out: function() { $closeLink.trigger('click'); }

            });

          } else {

            $cluetip.hover(doNothing, 

            function() {$closeLink.trigger('click'); });

          }

        } else {

          $cluetip.unbind('mouseout');

        }

      }

// now that content is loaded, finish the positioning 

      var direction = '';

      $cluetipOuter.css({overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight});

      tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(),$cluetip.height()) : parseInt(defHeight,10);   

      tipY = posY;

      baseline = sTop + wHeight;

      if (opts.positionBy == 'fixed') {

        tipY = posY - opts.dropShadowSteps + tOffset;

      } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') {

        if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) { 

          tipY = mouseY - tipHeight - tOffset;

          direction = 'top';

        } else { 

          tipY = mouseY + tOffset;

          direction = 'bottom';

        }

      } else if ( posY + tipHeight + tOffset > baseline ) {

        tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset;

      } else if ($this.css('display') == 'block' || $this[0].tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") {

        tipY = bpY - tOffset;

      } else {

        tipY = posY - opts.dropShadowSteps;

      }

      if (direction == '') {

        posX < linkLeft ? direction = 'left' : direction = 'right';

      }

      $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);

      if (opts.arrows) { // set up arrow positioning to align with element

        var bgY = (posY - tipY - opts.dropShadowSteps);

        $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show();

      } else {

        $cluetipArrows.hide();

      }



// (first hide, then) ***SHOW THE CLUETIP***

      $dropShadow.hide();

      $cluetip.hide()[opts.fx.open](opts.fx.open != 'show' && opts.fx.openSpeed);

      if (opts.dropShadow) $dropShadow.css({height: tipHeight, width: tipInnerWidth}).show();

      if ($.fn.bgiframe) { $cluetip.bgiframe(); }

      // trigger the optional onShow function

      if (opts.delayedClose > 0) {

        closeOnDelay = setTimeout(cluetipClose, opts.delayedClose);

      }

      opts.onShow($cluetip, $cluetipInner);

      

    };



/***************************************

   =INACTIVATION

-------------------------------------- */

    var inactivate = function() {

      isActive = false;

      $('#cluetip-waitimage').hide();

      if (!opts.sticky || (/click|toggle/).test(opts.activation) ) {

        cluetipClose();

clearTimeout(closeOnDelay);        

      };

      if (opts.hoverClass) {

        $this.removeClass(opts.hoverClass);

      }

      $('.cluetip-clicked').removeClass('cluetip-clicked');

    };

// close cluetip and reset some things

    var cluetipClose = function() {

      $cluetipOuter 

      .parent().hide().removeClass().end()

      .children().empty();

      if (tipTitle) {

        $this.attr(opts.titleAttribute, tipTitle);

      }

      $this.css('cursor','');

      if (opts.arrows) $cluetipArrows.css({top: ''});

    };



/***************************************

   =BIND EVENTS

-------------------------------------- */

  // activate by click

      if ( (/click|toggle/).test(opts.activation) ) {

        $this.click(function(event) {

          if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) {

            activate(event);

            $('.cluetip-clicked').removeClass('cluetip-clicked');

            $this.addClass('cluetip-clicked');



          } else {

            inactivate(event);



          }

          this.blur();

          return false;

        });

  // activate by focus; inactivate by blur    

      } else if (opts.activation == 'focus') {

        $this.focus(function(event) {

          activate(event);

        });

        $this.blur(function(event) {

          inactivate(event);

        });

  // activate by hover

    // clicking is returned false if cluetip url is same as href url

      } else {

        $this.click(function() {

          if ($this.attr('href') && $this.attr('href') == tipAttribute && !opts.clickThrough) {

            return false;

          }

        });

        //set up mouse tracking

        var mouseTracks = function(evt) {

          if (opts.tracking == true) {

            var trackX = posX - evt.pageX;

            var trackY = tipY ? tipY - evt.pageY : posY - evt.pageY;

            $this.mousemove(function(evt) {

              $cluetip.css({left: evt.pageX + trackX, top: evt.pageY + trackY });

            });

          }

        };

        if ($.fn.hoverIntent && opts.hoverIntent) {

          $this.mouseover(function() {$this.attr('title',''); })

          .hoverIntent({

            sensitivity: opts.hoverIntent.sensitivity,

            interval: opts.hoverIntent.interval,  

            over: function(event) {

              activate(event);

              mouseTracks(event);

            }, 

            timeout: opts.hoverIntent.timeout,  

            out: function(event) {inactivate(event); $this.unbind('mousemove');}

          });           

        } else {

          $this.hover(function(event) {

            activate(event);

            mouseTracks(event);

          }, function(event) {

            inactivate(event);

            $this.unbind('mousemove');

          });

        }

      }

    });

  };

  

/*

 * options for clueTip

 *

 * each one can be explicitly overridden by changing its value. 

 * for example: $.fn.cluetip.defaults.width = 200; 

 * would change the default width for all clueTips to 200. 

 *

 * each one can also be overridden by passing an options map to the cluetip method.

 * for example: $('a.example').cluetip({width: 200}); 

 * would change the default width to 200 for clueTips invoked by a link with class of "example"

 *

 */

  

  $.fn.cluetip.defaults = {  // set up default options

    width:            275,      // The width of the clueTip

    height:           'auto',   // The height of the clueTip

    cluezIndex:       99807,       // Sets the z-index style property of the clueTip

    positionBy:       'auto',   // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed'

    topOffset:        15,       // Number of px to offset clueTip from top of invoking element

    leftOffset:       15,       // Number of px to offset clueTip from left of invoking element

    local:            false,    // Whether to use content from the same page for the clueTip's body

    hideLocal:        true,     // If local option is set to true, this determines whether local content

                                // to be shown in clueTip should be hidden at its original location

    attribute:        'rel',    // the attribute to be used for fetching the clueTip's body content

    titleAttribute:   'title',  // the attribute to be used for fetching the clueTip's title

    splitTitle:       '',       // A character used to split the title attribute into the clueTip title and divs

                                // within the clueTip body. more info below [6]

    showTitle:        true,     // show title bar of the clueTip, even if title attribute not set

    cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass.

    hoverClass:       '',       // class applied to the invoking element onmouseover and removed onmouseout

    waitImage:        true,     // whether to show a "loading" img, which is set in jquery.cluetip.css

    cursor:           'pointer',

    arrows:           false,    // if true, displays arrow on appropriate side of clueTip

    dropShadow:       false,     // set to false if you don't want the drop-shadow effect on the clueTip

    dropShadowSteps:  6,        // adjusts the size of the drop shadow

    sticky:           false,    // keep visible until manually closed

    mouseOutClose:    false,    // close when clueTip is moused out

    activation:       'hover',  // set to 'click' to force user to click to show clueTip

                                // set to 'focus' to show on focus of a form element and hide on blur

    clickThrough:     false,    // if true, and activation is not 'click', then clicking on link will take user to the link's href,

                                // even if href and tipAttribute are equal

    tracking:         false,    // if true, clueTip will track mouse movement (experimental)

    delayedClose:     0,        // close clueTip on a timed delay (experimental)

    closePosition:    'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'

    closeText:        'Close',  // text (or HTML) to to be clicked to close sticky clueTips

    truncate:         0,        // number of characters to truncate clueTip's contents. if 0, no truncation occurs



    // effect and speed for opening clueTips

    fx: {             

                      open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'

                      openSpeed:  ''

    },     



    // settings for when hoverIntent plugin is used             

    hoverIntent: {    

                      sensitivity:  3,

              			  interval:     50,

              			  timeout:      0

    },



    // function to run just before clueTip is shown.           

    onActivate:       function(e) {return true;},



    // function to run just after clueTip is shown.

    onShow:           function(ct, c){},

    

    // whether to cache results of ajax request to avoid unnecessary hits to server    

    ajaxCache:        true,  



    // process data retrieved via xhr before it's displayed

    ajaxProcess:      function(data) {

                        data = data.replace(/<s(cript|tyle)(.|\s)*?\/s(cript|tyle)>/g, '').replace(/<(link|title)(.|\s)*?\/(link|title)>/g,'');

                        return data;

    },                



    // can pass in standard $.ajax() parameters, not including error, complete, success, and url

    ajaxSettings: {   

                      dataType: 'html'

    },

    debug: false

  };





/*

 * Global defaults for clueTips. Apply to all calls to the clueTip plugin.

 *

 * @example $.cluetip.setup({

 *   insertionType: 'prependTo',

 *   insertionElement: '#container'

 * });

 * 

 * @property

 * @name $.cluetip.setup

 * @type Map

 * @cat Plugins/tooltip

 * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'

 * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.

 *

 */

   

  var insertionType = 'appendTo', insertionElement = 'body';

  $.cluetip = {};

  $.cluetip.setup = function(options) {

    if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {

      insertionType = options.insertionType;

    }

    if (options && options.insertionElement) {

      insertionElement = options.insertionElement;

    }

  };

  







/*///////////////////////////This is the pop up//////////////////*/

//////////////////////////////////////////////////////////////////////

/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */

  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
       loading_image : '/images/global/wait.gif',
       close_image   : '/images/global/skin/closerX.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="contentFace"> \
                </div> \
                <div class="footerFace"> \
                  <a href="#" class="close"> \
                    <img src="/images/global/skin/closerX.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .contentFace').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .contentFace').addClass(klass)
      $('#facebox .contentFace').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      //.css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .contentFace').removeClass().addClass('contentFace')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);
			
			
/* ========================================================
 *  Jquery used on productDetail.aspx 
 * ======================================================== */
/**
 *  jQuery Plugin highlightFade (jquery.offput.ca/highlightFade)
 *  (c) 2006 Blair Mitchelmore (offput.ca) blair@offput.ca
 */
/**
 * This is version 0.7 of my highlightFade plugin. It follows the yellow fade technique of Web 2.0 fame
 * but expands it to allow any starting colour and allows you to specify the end colour as well.
 *
 * For the moment, I'm done with this plug-in. Unless I come upon a really cool feature it should have
 * this plug-in will only receive updates to ensure future compatibility with jQuery.
 *
 * As of now (Aug. 16, 2006) the plugin has been written with the 1.0.1 release of jQuery (rev 249) which
 * is available from http://jquery.com/src/jquery-1.0.1.js
 *
 * A note regarding rgb() syntax: I noticed that most browsers implement rgb syntax as either an integer 
 * (0-255) or percentage (0-100%) value for each field, that is, rgb(i/p,i/p,i/p); however, the W3C 
 * standard clearly defines it as "either three integer values or three percentage values" [http://www.w3.org/TR/CSS21/syndata.html] 
 * which I choose to follow despite the error redundancy of the typical behaviour browsers employ.
 *
 find attributes here
http://jquery.offput.ca/highlightFade/old.php
 */
jQuery.fn.highlightFade = function(settings) {
	var o = (settings && settings.constructor == String) ? {start: settings} : settings || {};
	var d = jQuery.highlightFade.defaults;
	var i = o['interval'] || d['interval'];
	var a = o['attr'] || d['attr'];
	var ts = {
		'linear': function(s,e,t,c) { return parseInt(s+(c/t)*(e-s)); },
		'sinusoidal': function(s,e,t,c) { return parseInt(s+Math.sin(((c/t)*90)*(Math.PI/180))*(e-s)); },
		'exponential': function(s,e,t,c) { return parseInt(s+(Math.pow(c/t,2))*(e-s)); }
	};
	var t = (o['iterator'] && o['iterator'].constructor == Function) ? o['iterator'] : ts[o['iterator']] || ts[d['iterator']] || ts['linear'];
	if (d['iterator'] && d['iterator'].constructor == Function) t = d['iterator'];
	return this.each(function() {
		if (!this.highlighting) this.highlighting = {};
		var e = (this.highlighting[a]) ? this.highlighting[a].end : jQuery.highlightFade.getBaseValue(this,a) || [255,255,255];
		var c = jQuery.highlightFade.getRGB(o['start'] || o['colour'] || o['color'] || d['start'] || [255,255,128]);
		var s = jQuery.speed(o['speed'] || d['speed']);
		var r = o['final'] || (this.highlighting[a] && this.highlighting[a].orig) ? this.highlighting[a].orig : jQuery.curCSS(this,a);
		if (o['end'] || d['end']) r = jQuery.highlightFade.asRGBString(e = jQuery.highlightFade.getRGB(o['end'] || d['end']));
		if (typeof o['final'] != 'undefined') r = o['final'];
		if (this.highlighting[a] && this.highlighting[a].timer) window.clearInterval(this.highlighting[a].timer);
		this.highlighting[a] = { steps: ((s.duration) / i), interval: i, currentStep: 0, start: c, end: e, orig: r, attr: a };
		jQuery.highlightFade(this,a,o['complete'],t);
	});
};

jQuery.highlightFade = function(e,a,o,t) {
	e.highlighting[a].timer = window.setInterval(function() { 
		var newR = t(e.highlighting[a].start[0],e.highlighting[a].end[0],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newG = t(e.highlighting[a].start[1],e.highlighting[a].end[1],e.highlighting[a].steps,e.highlighting[a].currentStep);
		var newB = t(e.highlighting[a].start[2],e.highlighting[a].end[2],e.highlighting[a].steps,e.highlighting[a].currentStep);
		jQuery(e).css(a,jQuery.highlightFade.asRGBString([newR,newG,newB]));
		if (e.highlighting[a].currentStep++ >= e.highlighting[a].steps) {
			jQuery(e).css(a,e.highlighting[a].orig || '');
			window.clearInterval(e.highlighting[a].timer);
			e.highlighting[a] = null;
			if (o && o.constructor == Function) o.call(e);
		}
	},e.highlighting[a].interval);
};

jQuery.highlightFade.defaults = {
	start: [255,255,128],
	interval: 50,
	speed: 400,
	attr: 'backgroundColor'
};

jQuery.highlightFade.getRGB = function(c,d) {
	var result;
	if (c && c.constructor == Array && c.length == 3) return c;
	if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))
		return [parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];
	else if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))
		return [parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];
	else if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))
		return [parseInt("0x" + result[1]),parseInt("0x" + result[2]),parseInt("0x" + result[3])];
	else if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))
		return [parseInt("0x"+ result[1] + result[1]),parseInt("0x" + result[2] + result[2]),parseInt("0x" + result[3] + result[3])];
	else
		return jQuery.highlightFade.checkColorName(c) || d || null;
};

jQuery.highlightFade.asRGBString = function(a) {
	return "rgb(" + a.join(",") + ")";
};

jQuery.highlightFade.getBaseValue = function(e,a,b) {
	var s, t;
	b = b || false;
	t = a = a || jQuery.highlightFade.defaults['attr'];
	do {
		s = jQuery(e).css(t || 'backgroundColor');
		if ((s  != '' && s != 'transparent') || (e.tagName.toLowerCase() == "body") || (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end)) break; 
		t = false;
	} while (e = e.parentNode);
	if (!b && e.highlighting && e.highlighting[a] && e.highlighting[a].end) s = e.highlighting[a].end;
	if (s == undefined || s == '' || s == 'transparent') s = [255,255,255];
	return jQuery.highlightFade.getRGB(s);
};

jQuery.highlightFade.checkColorName = function(c) {
	if (!c) return null;
	switch(c.replace(/^\s*|\s*$/g,'').toLowerCase()) {
		case 'aqua': return [0,255,255];
		case 'black': return [0,0,0];
		case 'blue': return [0,0,255];
		case 'fuchsia': return [255,0,255];
		case 'gray': return [128,128,128];
		case 'green': return [0,128,0];
		case 'lime': return [0,255,0];
		case 'maroon': return [128,0,0];
		case 'navy': return [0,0,128];
		case 'olive': return [128,128,0];
		case 'purple': return [128,0,128];
		case 'red': return [255,0,0];
		case 'silver': return [192,192,192];
		case 'teal': return [0,128,128];
		case 'white': return [255,255,255];
		case 'yellow': return [255,255,0];
	}
};



