
(function($) {

/**
 * Drupal FieldGroup object.
 */
Drupal.FieldGroup = Drupal.FieldGroup || {};
Drupal.FieldGroup.Effects = Drupal.FieldGroup.Effects || {};
Drupal.FieldGroup.groupWithfocus = null;

Drupal.FieldGroup.setGroupWithfocus = function(element) {
  element.css({display: 'block'});
  Drupal.FieldGroup.groupWithfocus = element;
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processFieldset = {
  execute: function (context, settings, type) {
    if (type == 'form') {
      // Add required fields mark to any fieldsets containing required fields
      $('fieldset.fieldset').each(function(i){
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $('legend span.fieldset-legend', $(this)).eq(0).append('&nbsp;').append($('.form-required').eq(0).clone());
        }
        if ($('.error', $(this)).length) {
          $('legend span.fieldset-legend', $(this)).eq(0).addClass('error');
          Drupal.FieldGroup.setGroupWithfocus($(this));
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processAccordion = {
  execute: function (context, settings, type) {
    var accordions = $('div.field-group-accordion-wrapper', context).accordion({
      autoHeight: false,
      active: 0,
      collapsible: true
    });
    if (type == 'form') {
      // Add required fields mark to any element containing required fields
      $('div.accordion-item').each(function(i){
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $('h3.ui-accordion-header').eq(i).append('&nbsp;').append($('.form-required').eq(0).clone());
        }
        if ($('.error', $(this)).length) {
          $('h3.ui-accordion-header').eq(i).addClass('error');
          var activeOne = $(this).parent().accordion("activate" , i);
          $('.ui-accordion-content-active', activeOne).css({height: 'auto', width: 'auto', display: 'block'});
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processHtabs = {
  execute: function (context, settings, type) {
    if (type == 'form') {
      // Add required fields mark to any element containing required fields
      $('fieldset.horizontal-tabs-pane').each(function(i){
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $(this).data('horizontalTab').link.find('strong:first').after($('.form-required').eq(0).clone()).after('&nbsp;');
        }
        if ($('.error', $(this)).length) {
          $(this).data('horizontalTab').link.parent().addClass('error');
          Drupal.FieldGroup.setGroupWithfocus($(this));
          $(this).data('horizontalTab').focus();
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 */
Drupal.FieldGroup.Effects.processTabs = {
  execute: function (context, settings, type) {
    if (type == 'form') {
      // Add required fields mark to any fieldsets containing required fields
      $('fieldset.vertical-tabs-pane').each(function(i){
        if ($(this).is('.required-fields') && $(this).find('.form-required').length > 0) {
          $(this).data('verticalTab').link.find('strong:first').after($('.form-required').eq(0).clone()).after('&nbsp;');
        }
        if ($('.error', $(this)).length) {
          $(this).data('verticalTab').link.parent().addClass('error');
          Drupal.FieldGroup.setGroupWithfocus($(this));
          $(this).data('verticalTab').focus();
        }
      });
    }
  }
}

/**
 * Implements Drupal.FieldGroup.processHook().
 * 
 * TODO clean this up meaning check if this is really 
 *      necessary.
 */
Drupal.FieldGroup.Effects.processDiv = {
  execute: function (context, settings, type) {

    $('div.collapsible', context).each(function() {
      var $wrapper = $(this);

      // Turn the legend into a clickable link, but retain span.field-group-format-toggler
      // for CSS positioning.
      var $toggler = $('span.field-group-format-toggler:first', $wrapper);
      var $link = $('<a class="field-group-format-title" href="#"></a>');
      $link.prepend($toggler.contents()).appendTo($toggler);
      
      // .wrapInner() does not retain bound events.
      $link.click(function () {
        var wrapper = $wrapper.get(0);
        // Don't animate multiple times.
        if (!wrapper.animating) {
          wrapper.animating = true;
          var speed = $wrapper.hasClass('speed-fast') ? 300 : 1000;
          if ($wrapper.hasClass('effect-none') && $wrapper.hasClass('speed-none')) {
            $('> .field-group-format-wrapper', wrapper).toggle();
          }
          else if ($wrapper.hasClass('effect-blind')) {
            $('> .field-group-format-wrapper', wrapper).toggle('blind', {}, speed);
          }
          else {
            $('> .field-group-format-wrapper', wrapper).toggle(speed);
          }
          wrapper.animating = false;
        }
        return false;
      });
      
    });
  }
};

/**
 * Behaviors.
 */
Drupal.behaviors.fieldGroup = {
  attach: function (context, settings) {
    if (settings.field_group == undefined) {
      return;
    }
    $('body', context).once('fieldgroup-effects', function () {
      // Execute all of them.
      $.each(Drupal.FieldGroup.Effects, function (func) {
        // We check for a wrapper function in Drupal.field_group as 
        // alternative for dynamic string function calls.
        var type = func.toLowerCase().replace("process", "");
        if (settings.field_group[type] != undefined && $.isFunction(this.execute)) {
          this.execute(context, settings, settings.field_group[type]);
        }
      });
    });
  }
};

})(jQuery);;
(function($) {
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
		var oldCurCSS = $.curCSS;
		$.curCSS = function(elem, name, force){
			if(name === 'background-position'){
				name = 'backgroundPosition';
			}
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
	
	var oldAnim = $.fn.animate;
	$.fn.animate = function(prop){
		if('background-position' in prop){
			prop.backgroundPosition = prop['background-position'];
			delete prop['background-position'];
		}
		if('backgroundPosition' in prop){
			prop.backgroundPosition = '('+ prop.backgroundPosition;
		}
		return oldAnim.apply(this, arguments);
	};
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			var end = toArray(fx.end);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		//return;
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);;
  //jQuery(document).ready(function() {
  var loadingImg;
  var baseUrl;
  var moreImg;
  var readMorTxt;
  var closeImg;
  var CurrentlocationUrl;
  var cajax;
  var cajaxUrl;
  var ajaxHrefVal;
  var browserHeight;
  Drupal.behaviors.globalJsFns = {
  attach: function(context) {
	//alert('inn');
		  jQuery(".page-article-163 .page_tpl_content .content .view-dom-id-2,.page-article-187 .view-display-id-page,.page-article-189 .view-display-id-page").append("<div class='apply_now_btn'><a href='apply-job'>Apply Now</a></div>");

	/*var basePath = Drupal.settings.basePath;
	var baseUrl = window.location.protocol+'//'+window.location.hostname+basePath;
    jQuery.extend(Drupal.settings, { "basePath": baseUrl });
  	alert(Drupal.settings.basePath+'====glo');*/
	
	//create a new element link with your link
   		// baseUrl = Drupal.settings.basePath; 24, 25, 27, 28, 740, 767, 1032, 1046, 1052, 1069, 1101
		baseUrl = Drupal.settings.baseURL;
		moreImg = baseUrl+"/sites/default/files/more.png"; 
		readMorTxt = Drupal.t("Read More");
		loadingImg = baseUrl+'/sites/default/files/loading.gif';
		closeImg = baseUrl+'/sites/default/files/Close-hover.jpg';
		CurrentlocationUrl = window.location.href;
		cajax = CurrentlocationUrl.split("#cajax=");
		cajaxUrl = cajax[1];
		//alert(cajaxUrl);
		if(ajaxHrefVal == undefined && cajaxUrl != undefined){
			ajaxHrefVal = true;
			jQuery(".page_middle_content").css({'min-height':500}).html("");
			customAjax(cajaxUrl);
		}
		
		
		
		//browserHeight = (jQuery(window).height() > jQuery(document).height()) ? jQuery(window).height() : jQuery(document).height();		
		//alert(browserHeight);
		//jQuery(".center_bg_transparent").attr({"height":browserHeight});	
		//#cajax=
		//setTimeout("centerBgTransparent()",1000);
		//alert(locationUrl);
  	 	
		/** Search box */
		jQuery(".search_block #edit-search-block-form--2").val("Search");
		jQuery(".search_block #edit-search-block-form--2").focus(function(){
			if(jQuery(".search_block #edit-search-block-form--2").val() == "Search")
				jQuery(".search_block #edit-search-block-form--2").val("");
		})
		jQuery(".search_block #edit-search-block-form--2").blur(function(){
			if(jQuery(".search_block #edit-search-block-form--2").val() == "")
				jQuery(".search_block #edit-search-block-form--2").val("Search");
		})
		/** Search box */		
		
		
		/** Facebook Icon replace on footer link */
		//alert(jQuery(".footer_menu ul li.last").html());
		//var footerLastMenu = jQuery(".footer_menu ul li.last a").html();
		//footerLastMenu = '<img src="'+baseUrl+'sites/default/files/facebook-icon.png" class="facebook_icon" /> Facebook';
		//jQuery(".footer_menu ul li.last a").html(footerLastMenu);
		/** Facebook Icon replace on footer link */
		
		
		/** jquery submenu hover animation */
		
		
		/* Sample
		$('#a a')
			.css( {backgroundPosition: "-20px 35px"} )
			.mouseover(function(){
				$(this).stop().animate({backgroundPosition:"(-20px 94px)"}, {duration:500})
			})
			.mouseout(function(){
				$(this).stop().animate({backgroundPosition:"(40px 35px)"}, {duration:200, complete:function(){
					$(this).css({backgroundPosition: "-20px 35px"})
				}})
			})
		*/
		
		var hoverTmp = true;
		jQuery(".sub_menu_block_ul li a").hover(function(){
			var activeDiv = jQuery(this).find(".active").html();
			if(activeDiv == null){
			if(hoverTmp == true)	{
				hoverTmp = false;
				//alert(hoverTmp);
				//jQuery(this).find("span").css({'margin-top':26, 'color':'#fff'}).hide();
				jQuery(this).find("span").css({'color':'#fff','font-weight':'normal'});
				//jQuery(this).find("span").css({'margin-top':26, 'color':'#fff','font-weight':'normal'}).hide();
			//	jQuery(this).find(".menu-title-first").css({'font-weight':'normal'});
				//jQuery(this).find(".menu-title-second").css({'font-weight':'normal'});
				jQuery(this).find(".sub_menu_item_text").animate({backgroundPosition: '0px 0px'}, {duration:200, complete:function(){
					//showTxt(this);
					/*jQuery(this).find("span").show();
					jQuery(this).find("span").animate({
				   		marginTop: 3
					}, 150, function() {
					});*/
					
				}});
			
				//jQuery(this).find(".sub_menu_item_text").css({"background-position":"0"});
			} else if(hoverTmp == false){
				hoverTmp = true;
				//alert(hoverTmp);
				//jQuery(this).find(".sub_menu_item_text").css({"background-position":"0 25px"});
				jQuery(this).find(".sub_menu_item_text").animate({backgroundPosition: '0px 33px'}, {duration:200, complete:function(){
					//showTxt(this);
					//jQuery(this).find("span").css({'margin-top':25});
				}});
				jQuery(this).find("span").css({'color':'#000','font-weight':'bold'});
				jQuery(this).next(".menu-title-second").css({'font-weight':'bold'});
				/*jQuery(this).find("span").animate({
				   		marginTop: 26
					}, 150, function() {
						jQuery(this).css({'margin-top':'3px', 'color':'#000'});
						//jQuery(this).next(".menu-title-second").css({'font-weight':'bold'});
					});*/


				}
				
			}
		})
		/** jquery submenu hover animation end */
		
		/** jquery topmenu hover animation start */
		var topHoverTmp = true;
		jQuery(".top_menu li").hover(function(){
			var activeDiv = jQuery(this).find(".active-trail").html();
			if(activeDiv == null){
			if(topHoverTmp == true)	{
				topHoverTmp = false;
				jQuery(this).animate({backgroundPosition: '0px 0px'}, {duration:200, complete:function(){
				}});
			} else if(topHoverTmp == false){
				topHoverTmp = true;
				jQuery(this).animate({backgroundPosition: '0px 40px'}, {duration:200, complete:function(){
				}});
				}
				
			}			
			
			
		});
		

		
		jQuery('a[href="http://locator.ashokleyland.com/dealersmap/searchlocation/index"]').attr({"target":"_blank"});
		jQuery("#menu-897-1 ul li a").attr({"target":"_blank"});
		//jQuery("#menu-897-1 ul li a").attr({"target":"_blank"});
		
		/** jquery topmenu hover animation end */
		
		/** custom lightbox */
		
		jQuery('a[rel="customlightbox"]').click(function(){

			var hrefVal = jQuery(this).attr("href");
			if(hrefVal == '#'){
				return false;
			}
			//alert(idVal);
			openCustomLightBox(this,hrefVal);
			//openCustomLightBox(hrefVal,idVal);
			return false;
		
		});
		
		
		//jQuery(".view-joint-ventures")
		
		jQuery('a[rel="customAjax"]').click(function(){
			var thisUrl = jQuery(this).attr('href');
			thisUrl = thisUrl.split("#cajax=");
			//var rightClickHref = window.location.href+"#cajax="+jQuery(this).attr('href');
			if(thisUrl[1] != undefined)
				ajaxHrefVal = thisUrl[0];
			else
				ajaxHrefVal = jQuery(this).attr("href");
				//alert(ajaxHrefVal);
				//return false;
				
			/*	//jQuery(".page_middle_content").html(data);
				
				/*
			if(ajaxHrefVal.indexOf("manufacturing-facilities") != -1){
				jQuery(".view-manufacturing-facilities .views-row a img").css({'border':'0'});
				jQuery('a[href="'+ajaxHrefVal+'"]').find('img').css({'border':'2px solid #027FBE'});		
			}
			*/
			
			
			customAjax(ajaxHrefVal);
			//window.location.href = '#cajax='+ajaxHrefVal;//vinoth
			//alert("tes");
			//Drupal.attachBehaviors(".page_middle_content");
			return false;
		
		});

		jQuery('.scroll-pane,.page-product-details .view-product-details .content').jScrollPane();
		
			/** Our Products */
			/*jQuery('.page-our-products .views-row').css({'margin-right':0});*/
			/*jQuery('.page-our-products .view-products .views-row').filter(function(index) {
	  				return index % 4 == 3;
			}).css('margin-right', 0);*/
			//jQuery(".page-our-products .view-products .views-row-last").after("<div class='clear'></div>");
			/** Our Products */
			//alert(jQuery(".readmor_img").attr("src"));
			//if(jQuery(".readmor_img").)
			
			if(jQuery(".page-article-163")){
			
			//    jQuery(".page-our-products .view-products .views-field-body .field-content a p,.views-field-field-related-desc a").append("<hr>");
			     
			}else{
			   
           if(jQuery(".readmor_img").attr("src") == undefined)
			     jQuery(".page-our-products .view-products .views-field-body .field-content a p,.views-field-field-related-desc a").append("<img class='readmor_img' src='"+moreImg+"' title='"+readMorTxt+"' alt='"+readMorTxt+"' />");
			
      
      }
      
			

		
		/** selectBox Style */
		jQuery('.form-select').customSelectBoxStyle();
		
		jQuery(".conference-call-document-block .file a, .view-annual-reports .file a").html("Download PDF");
		
		jQuery(".page-journals .views-field-field-journal-attchmnt .file a").after("<div class='journal-archives-link'><a href='"+baseUrl+"/ashley-archive'></a></div>");
		jQuery(".page-journals .views-field-field-milestone-attachment .file a").after("<div class='journal-archives-link'><a href='"+baseUrl+"/milestone-archive'></a></div>");
		jQuery(".page-journals .page_tpl_content_bottom").after("<div class='supplier_connect_journal'><div class='view-content'><div class='views-field views-field-title'><span>Supplier Connect</span></div><div class='supplier_connect_journal_link_container'><a class='latest' href='http://supplierconnect.ashokleyland.com' target='blank'></a><a class='archives' href='http://supplierconnect.ashokleyland.com/?post_type=newsletter-archives' target='blank'></a><div class='clear'></div></div></div></div>");
		
		
		jQuery(".view-shareholder-pattern .views-row").each(function(){
			//jQuery(this).find(".views-field-field-shareholder-pdf-file a").html(jQuery.trim(jQuery(this).find(".views-field-title").text())+".pdf");
			jQuery(this).find(".views-field-field-shareholder-pdf-file a").html("Download PDF");
		});
		
		jQuery(".view-corporage-governance-quarterly-r .views-row").each(function(){
			jQuery(this).find(".file a").html(jQuery.trim(jQuery(this).find(".corp-gov-quarterly-report-title").text()));
		});
		
		jQuery("#al_body_table_contents tr td .Apple-style-span").css({'color':'#222'});
		
		//jQuery(".view-shareholder-pattern .views-field-field-shareholder-pdf-file").html(jQuery(".view-shareholder-pattern .views-field-title").text());
		
	//jQuery("select").selectBox();
	
	 /*jQuery('a[rel="customAjax"]').contextMenu(function(){
	 	alert("test");
	 })*/
		
		/*jQuery('a[rel="customAjax"]').bind('rightclick', function(){ 
    alert('right mouse button is pressed');
});*/

jQuery('a[rel="customAjax"]').mousedown(function(event) {
    switch (event.which) {
        case 1:
            //alert('Left mouse button pressed');
            break;
        case 2:
           // alert('Middle mouse button pressed');
            break;
        case 3:
            //alert('Right mouse button pressed');
			//alert(jQuery(this).attr('href'));
			//alert(window.location.href);
			var thisUrl = jQuery(this).attr('href');
			thisUrl = thisUrl.split("#cajax=");
			var windowUrl = window.location.href;
			windowUrl = windowUrl.split("#cajax=");
			
			if(windowUrl[1] != undefined)
				var currentUrl = windowUrl[0];
			else
				var currentUrl = window.location.href;			
			
			var rightClickHref = currentUrl+"#cajax="+jQuery(this).attr('href');
			if(thisUrl[1] == undefined)
				jQuery(this).attr('href',rightClickHref);
			//alert(rightClickHref);
            break;
        default:
            alert('You have a strange mouse');
    }
});





		
		/*jQuery(document).bind("contextmenu", function(e) {
		//alert(jQuery('a[rel="customAjax"]').attr("href"));
		alert(jQuery(e).parent().html());
			//alert(jQuery(e).html());
			//alert("reasr");
			//alert(dtc(this).html());
			//alert(jQuery(e).attr("href"));
			return false;
		});*/
		
		var start_from = 1;
		//jQuery('.myCarousel .views-row').each(function(){
		    jQuery('.myCarousel .views-row').find(".active").parent().addClass("active");
    //});
    //alert(jQuery('.myCarousel .views-row').find('.active').parent().index());
    
    start_from = jQuery('.myCarousel .views-row').find('.active').parent().index();
    if(start_from == undefined) start_from = 1;
		
		jQuery('.myCarousel').jcarousel({
        vertical: true,
        scroll: 4,
        visible:4,
        start:start_from
    });
   
   /* 
    jQuery('#block-views-article-block-2').find(".active").parent().parent().parent().css({'background-color':'#ccc'});
    jQuery('#block-views-annual-reports-block-2').find(".active").parent().parent().parent().css({'background-color':'#ccc'});
    
    jQuery('#block-views-depository-system-block-2').find(".active").parent().parent().parent().css({'background-color':'#ccc'});
    jQuery('#block-views-physical-segment-block-2').find(".active").parent().parent().parent().css({'background-color':'#ccc'});
    jQuery('#block-views-investor-info-block-2').find(".active").parent().parent().parent().css({'background-color':'#ccc'});
    jQuery('#block-views-investor-update-2-block-2').find(".active").parent().parent().parent().css({'background-color':'#ccc'});
     */
    jQuery('.view-content').find(".active").parent().parent().parent().addClass('active');
    
    
 /*   jQuery('.view-media-gallery #media-kit ul li:first').addClass("active");
    jQuery('#block-views-media-gallery-block #media-kit ul li:first').addClass("active");*/
    
    
    
	//setJointVentureHeight();
	//setTimeout("jointVentureSetHeight()",1000);
	
	/*jQuery(".view-associate-company .view-content .views-row").each(function(){
		var panelHeight = "";
		panelHeight = jQuery(this).height();
		var imageHeight;
		imageHeight = jQuery(this).find(".views-field-field-associate-company-logo").height();
		var diffHeight;
		diffHeight = panelHeight-imageHeight;
		
			jQuery(this).find(".views-field-field-associate-company-logo").css({"margin-top":diffHeight});
	});*/
	jQuery(".view-leadership-team .view-content h3:eq(1)").next("div.ui-accordion-content").each(function(){
		jQuery(this).find(".profilie_dash_board_image a").removeAttr('rel');
		jQuery(this).find(".profilie_dash_board_image a").attr({'href':'#','style':'cursor:default'});
		jQuery(this).find(".profilie_dash_board_title a").removeAttr('rel');
		jQuery(this).find(".profilie_dash_board_title a").attr({'href':'#','style':'cursor:text'});
	});
	
	jQuery(".view-leadership-team .view-content h3:eq(0)").next("div.ui-accordion-content").find(".views-field-title").remove();
	
	jQuery('#media-kit .views-field-field-media-kit-image img').click(function(){
		var fileName = jQuery(this).parent().parent().parent().parent().find(".views-field-field-mk-upload-pdf .file a").text();
		document.getElementById('media-kit-hidden-file').value = fileName;
	 });
	 
	if(jQuery(".media-gallery-heading").text() == '') 
		jQuery(".page-media-kit #block-system-main .view-display-id-page_1").before("<h2 class='block-title media-gallery-heading'>Media Gallery</h2>");
	 
	 
	 jQuery('.view-media-gallery .media_kit_cls:first').addClass("media_active");
	 	 jQuery('.view-media-gallery .media_kit_cls:gt(0)').hide();
	 
	 var media_kit_tabs_list = '';
	 var media_kit_tabs_list_cnt = 0;
	 jQuery(".media_kit_cls .photo .topic .set").each(function(){
	//alert(jQuery(this).text());
	 	media_kit_tabs_list +="<div id='media_kit_tabs_id_"+media_kit_tabs_list_cnt+"'>"+jQuery(this).text()+"</div>";
		media_kit_tabs_list_cnt++;
	 });
	// alert(media_kit_tabs_list);
	if(jQuery(".media_kit_tabs").text() == ""){
		jQuery(".view-id-media_gallery").before("<div class='media_kit_tabs'>"+media_kit_tabs_list+"</div>");	
	}
	 jQuery(".media_kit_tabs div:first").addClass("media_kit_tab_active");
	 
	 //var mediaHoverCnt = 0;
	 jQuery(".media_kit_tabs div").hover(function(){
	 var activTabIndex = jQuery(this).index();
	  jQuery('.view-media-gallery .media_kit_cls').removeClass("media_active").hide();
	 jQuery('.view-media-gallery .media_kit_cls:eq('+activTabIndex+')').addClass("media_active").show();
	 	jQuery(".media_kit_tabs div").removeClass("media_kit_tab_active");
		jQuery(this).addClass("media_kit_tab_active");		 	
	 })
	 
	 /*jQuery(".page-media-kit .view-display-id-page_1 .view-content #media-kit").each(function(){
	 //	alert(jQuery(this).height());
	 });*/
	/* var mediaHover = 0;
	 jQuery(".page-media-kit .view-display-id-page_1 .view-content #media-kit").hover(function(){
	 	//alert("tast");
		if(mediaHover == 0){
			mediaHover = 1;
			//alert(jQuery(this).find("ul li ul").height());
			jQuery(".page-media-kit .view-display-id-page_1 .view-content #media-kit ul li ul").hide();
			jQuery(".page-media-kit .view-display-id-page_1 .view-content #media-kit ul li a").css({'color':'#000','background':'#bbb'});
			jQuery(this).find("ul li a").css({'color':'#fff','background':'#aaa'});
			jQuery(this).find("ul li ul").attr({'style':'display:block; position:absolute; left:0; top:31px; list-style:none; padding:0; margin:0;background:#ddd; width:464px; padding:50px 60px; border:20px solid #aaa; z-index:1;'});	
			var setMediaHeight = jQuery(this).find("ul li ul").height() + 199;
			
			if(navigator.appVersion.indexOf("MSIE 7") != -1) {
					var setMediaHeight = jQuery(this).find("ul li ul").height() + 199;
			}
			
			jQuery(".page-media-kit .view-display-id-page_1").height(setMediaHeight);
		} else{
			mediaHover = 0;
			//jQuery(".page-media-kit .view-display-id-page_1").height(290);			
		}

	 });*/
	 
	 /* var mediaCIHover = 0;
	 jQuery(".page-media-kit #block-views-media-gallery-block #media-kit").hover(function(){
	 	//alert("tast");
		if(mediaHover == 0){
			mediaHover = 1;
			//alert(jQuery(this).find("ul li ul").height());
			jQuery(".page-media-kit #block-views-media-gallery-block #media-kit ul li ul").hide();
			jQuery(".page-media-kit #block-views-media-gallery-block #media-kit ul li a").css({'color':'#000','background':'#bbb'});
			jQuery(this).find("ul li a").css({'color':'#fff','background':'#aaa'});
			jQuery(this).find("ul li ul").attr({'style':'display:block; position:absolute; left:0; top:31px; list-style:none; padding:0; margin:0;background:#ddd; width:464px; padding:50px 60px; border:20px solid #aaa; z-index:100;'});	
			var setMediaHeight = jQuery(this).find("ul li ul").height() + 199;
			
			if(navigator.appVersion.indexOf("MSIE 7") != -1) {
					var setMediaHeight = jQuery(this).find("ul li ul").height() + 199;
			}
			
			jQuery(".page-media-kit #block-views-media-gallery-block").height(setMediaHeight);
		} else{
			mediaHover = 0;
			//jQuery(".page-media-kit .view-display-id-page_1").height(290);		
		}

	 });*/
	 
	
	/** Menu Active Link Removal */
	jQuery(".page_tpl_left .sub_menu_block_ul li a .active").parent("a").attr({"href":'#'}).css({'cursor':'default'});
	jQuery(".top_menu a.active-trail,#block-menu-block-1 .menu-block-wrapper a.active-trail,#block-menu-block-1 .menu-block-wrapper li.active a").attr({"href":'#'}).css({'cursor':'default'});
	
	
	/**Set Target Blank */ 
	jQuery(".page-article-212 .page_tpl_bottom_right .views-row-last a,.page-article-213 .page_tpl_bottom_right .views-row-first a,.page-article-215 .page_tpl_bottom_right .views-row-last a,.page-article-216 .page_tpl_bottom_right .views-row-last a,.page-group-companies .block-menu-block .content .menu-block-wrapper a").attr({"target":"_blank"});
	/*jQuery(".file a").each(function(){
		var chkFileType = jQuery(this).attr("type");	
		//alert(chkFileType.indexOf("application/pdf"));
		if(chkFileType.indexOf("application/pdf") == 0){
			jQuery(this).attr({"target":"_blank"});
		}
	});*/
	
	jQuery(".file a").click(function(){
		var chkFileType = jQuery(this).attr("type");	
		var chkFileName = jQuery(this).attr("href");
		chkFileName = jQuery.trim(chkFileName);
    	var pdfFileName = chkFileName.split(baseUrl);
    	pdfFile = pdfFileName[1];	
		if(pdfFile == undefined)
		pdfFile = pdfFileName;
		//alert(pdfFileName);
		//alert(chkFileName);
		if(chkFileType.indexOf("application/pdf") == 0){
			window.location.href = baseUrl+"/pdf-file-download?wfid="+pdfFile;
			return false;
		}
	});
	
	
	/**Accordion hover style */
	var accHover = true;
	jQuery(".ui-accordion-header").hover(function(){
		if(accHover == true){
			accHover = false;
			//jQuery(this).find(".ui-icon").addClass("ui-icon-triangle-1-s").removeClass("ui-icon-triangle-1-e");				
			jQuery(this).find("a,a span").addClass("accordion-span-hover");
			//jQuery(this).find("a").addClass("accordion-span-hover");
		} else{
			accHover = true;
			//alert(jQuery(".ui-state-active a span").text());
			jQuery(this).find("a,a span").removeClass("accordion-span-hover");	
			//jQuery(this).find(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");				
		}
	});
	
	/** Contact Us heading */
	jQuery(".page-contact-us .page_middle_content").before("<h2 class='contact_title'>Contact Us</h2>");
	
	/** Contact Us Inline Accordion */
	
	
	jQuery(".page-contact-us .view-contact-us").before('<div class="country_container_div">&nbsp;</div>');
	jQuery(".page-contact-us .views-row-first table").hide();
	jQuery(".page-contact-us .views-row-first table.first-table").show();
	//jQuery(".page-contact-us .views-row-first table div.contact_sub_sub_heading").css({'display':'block'});
	/*jQuery(".contact_sub_sub_heading").next("div").hide();*/
	jQuery(".contact_sub_sub_heading").click(function(){
		jQuery(".contact_sub_sub_heading").next(".address_details").hide();
		jQuery(this).next(".address_details").show();
	});
  	var contactHeading = 1;
	jQuery(".page-contact-us .view-id-contact_us h3").each(function(){
		jQuery(this).attr({"id":"contact_heading_"+contactHeading});		
		contactHeading++;
	});
	jQuery("#contact_heading_1").next("div").show();
	jQuery(".page-contact-us .view-id-contact_us h3").click(function(){
		var BgImg = 'url("sites/all/themes/zen/zen-internals/images/active-hover-bg.png") no-repeat scroll left center transparent'
		jQuery(".page-contact-us .view-id-contact_us h3").css({'background':'transparent'});
		jQuery(".page-contact-us .view-id-contact_us h3").next("div").hide();
		jQuery(this).css({"background":BgImg});
		jQuery(this).next("div").show();
		
	})
  
  
	
	
	
	
	//jQuery(".page-contact-us .ui-accordion-content:eq(0) .views-row-first").before("<div id='inline_expand_collapse' class='expand'>Expand All</div><div class='clear'></div>");
	
	//var collapseSame = new Array;
	jQuery("#event_type_id").change(function () {
		var obj = jQuery('select option:selected').val(); 
		jQuery(".page-contact-us .views-row-first table").hide();
		jQuery(".page-contact-us .views-row-first table."+obj).show();
			//jQuery(".page-contact-us .views-row-first table").hide();
			//jQuery(this).next("table").show(200);	
			//alert(collapseSame[this]);
			//alert(jQuery(this).next("table").css('display'));
			/*var currTBLStatus = jQuery(this).next("table").css('display');
			jQuery(".page-contact-us .views-row-first .contactus_sup_heading").removeClass("enableArrow");
			jQuery(".page-contact-us .views-row-first table").hide(100);
			jQuery("#inline_expand_collapse").text("Expand All").attr({"class":"expand"})
			if(currTBLStatus == 'none'){
				jQuery(this).addClass("enableArrow");
				jQuery(this).next("table").show(100);					
			}*/
			
			/*
		if(collapseSame[this] == undefined || collapseSame[this] == true){
			//collapseSame[this] = false;
			jQuery(".page-contact-us .views-row-first table").hide();
			jQuery(this).next("table").show(200);	
			
		} else{
			collapseSame[this] = true;
			jQuery(".page-contact-us .views-row-first table").hide();
			jQuery(this).next("table").hide(200);	
		}*/
	});
	
	jQuery("#inline_expand_collapse").click(function(){
		var optVal = jQuery(this).attr("class");
		if(optVal == 'expand'){
			jQuery(this).text("Collapse All").attr({"class":"collapse"});
			jQuery(".page-contact-us .views-row-first .contactus_sup_heading").addClass("enableArrow");
			jQuery(".page-contact-us .views-row-first table").show();
		} else{
			jQuery(this).text("Expand All").attr({"class":"expand"});
			jQuery(".page-contact-us .views-row-first .contactus_sup_heading").removeClass("enableArrow");
			jQuery(".page-contact-us .views-row-first table").hide();			
		}
	});
	
	jQuery(".ui-accordion").before("<div style='float:right' id='customAccorion' class='expand'>Expand All</div><div class='clear'></div>");
	var tmpAcc;
	jQuery(".ui-accordion-header").click(function(){
		if(tmpAcc == undefined){
			return false;
		}
		//alert(tmpAcc);
		if(tmpAcc == true){
			/*jQuery("#customAccorion").click();*/
			tmpAcc = false;
			jQuery("#customAccorion").click();
			jQuery(".ui-accordion-header").click();
			return false;
			/*
			jQuery("#customAccorion").text("Collapse All").attr({"class":"collapse"});	
			var accHeaderCls = ".ui-accordion-header";
			var accContentCls = ".ui-accordion-content";
			customAccExpandCollapse("collapse",accHeaderCls,accContentCls);	*/
		}
		/*var currentIndex = jQuery(".ui-accordion-header").index(this);
		var accHeaderCls = ".ui-accordion-header:eq("+currentIndex+")";
		var accContentCls = ".ui-accordion-content:eq("+currentIndex+")";
		var currAccStatus = jQuery(this).next(".ui-accordion-content").css('display');
		//alert(currAccStatus);
		if(tmpAcc == true && currAccStatus == 'block'){
			var optVal = "collapse";
			customAccExpandCollapse(optVal,accHeaderCls,accContentCls);
			//tmpAcc = false;	
			//jQuery(".ui-accordion-content:eq(0)").hide();			
		}else{
			var optVal = "expand";
			customAccExpandCollapse(optVal,accHeaderCls,accContentCls);
		}
		return false;
		//else{
		//	var optVal = "expand";
		//	tmpAcc = true;	
			//jQuery(".ui-accordion-content:eq(0)").show();			
		//}
		//jQuery(".ui-accordion-header:eq(0)").click();*/
		
	});
	
	jQuery("#customAccorion").click(function(){
		var optVal = jQuery(this).attr("class");
		var accHeaderCls = ".ui-accordion-header";
		var accContentCls = ".ui-accordion-content";
		if(optVal == 'expand'){
			jQuery(this).text("Collapse All").attr({"class":"collapse"});
			tmpAcc = true;
		} else{
			jQuery(this).text("Expand All").attr({"class":"expand"});
			tmpAcc = false;			
		}
		
		//alert("test");
		/*jQuery(".ui-accordion-header:eq(0)").click();
		jQuery(".ui-accordion-header:eq(1)").click();
		jQuery(".ui-accordion-header:eq(2)").click();
		/*jQuery(".ui-accordion-header").each(function(){
			jQuery(this).click();
		});*/
		customAccExpandCollapse(optVal,accHeaderCls,accContentCls);
		/*jQuery(".ui-accordion-header:eq(0)").click();*/
		

			
		//ui-state-default ui-corner-all
		/*jQuery(".ui-accordion-content").slideDown('slow', function() {
    		// Animation complete.
			jQuery(".ui-accordion-content").addClass("ui-accordion-content-active");
			jQuery(".ui-accordion-header").addClass("ui-state-active ui-corner-top ui-state-focus");
			jQuery(".ui-accordion-header .ui-icon").removeClass("ui-icon-triangle-1-e");
			jQuery(".ui-accordion-header .ui-icon").addClass("ui-icon-triangle-1-s");
			//jQuery(".ui-accordion-header").remvoeClass("ui-state-focus");
			//jQuery(".ui-accordion-header").addClass("ui-state-active ui-corner-top ui-state-focus");
 		 });*/

	});
	
	/** Image flow year */
	//alert("taset");
	
	/*jQuery(".write_to_us_pop_up").click(function(){
		alert("test");
	});*/
	
	/** Captcha text */
	jQuery(".captcha .form-item-captcha-response label").html("Enter the characters shown in the image.<span title='This field is required.' class='form-required'>*</span>")
	jQuery(".captcha .form-item-captcha-response .description").remove();
	
	/**annual report*/
	jQuery(".page-performance-reports .views-row .annual-report-row").each(function(){
		if(jQuery(this).find(".annual-report-icon a").html() == null){
			jQuery(this).remove();
		}
	});
	
	/** Write to Us Default Select*/
	jQuery("#webform-client-form-856 #edit-submitted-queries-on option:eq(0)").val("");
	
	
	jQuery(".page_tpl_bottom_right2 #block-views-product-details-block-2 .pager-next").click(function(){
		jQuery(this).find("a").click();
	});
	
	jQuery(".page_tpl_bottom_right2 #block-views-product-details-block-2 .pager-previous").click(function(){
		jQuery(this).find("a").click();
	});
	
	jQuery(".view-press-releases-archive .views-field-field-press-release-file-upload .field-content").before("<div class='press_release_read_more'>Read More</div>");
	
	/*jQuery(".file .file-icon").css({"cursor":"pointer"});
	jQuery(".file .file-icon").click(function(){
		jQuery(this).next("a").click();	
	});*/
	
	jQuery(".view-press-releases-archive .views-field-title").click(function(){
		jQuery(".view-press-releases-archive .press_release_content,.view-press-releases-archive .views-field-field-press-published-from,.view-press-releases-archive .press_release_image").slideUp();
		jQuery(".view-press-releases-archive .press_release_two_liner").show();
		var chkOpen = jQuery(this).parent().find(".press_release_content").css("display");
		if(chkOpen == "none"){
			jQuery(this).parent().find(".press_release_two_liner").hide();			
			jQuery(this).parent().find(".press_release_content,.views-field-field-press-published-from,.press_release_image").slideDown();	
			
		}else{
			jQuery(this).parent().find(".press_release_content,.views-field-field-press-published-from,.press_release_image").slideUp();			
			jQuery(this).parent().find(".press_release_two_liner").show();						
		}
	});
	jQuery(".view-press-releases-archive .press_release_read_more").click(function(){
		jQuery(".view-press-releases-archive .press_release_content,.view-press-releases-archive .views-field-field-press-published-from,.view-press-releases-archive .press_release_image").slideUp();
		jQuery(".view-press-releases-archive .press_release_two_liner").show();
		var chkOpen = jQuery(this).parent().parent().find(".press_release_content").css("display");
		if(chkOpen == "none"){
			jQuery(this).parent().parent().find(".press_release_two_liner").hide();
			jQuery(this).parent().parent().find(".press_release_content,.views-field-field-press-published-from,.press_release_image").slideDown();			
		}else{
			jQuery(this).parent().parent().find(".press_release_content,.views-field-field-press-published-from,.press_release_image").slideUp();	
			jQuery(this).parent().parent().find(".press_release_two_liner").show();		
		}
	});
	
	
	jQuery("#menu-649-1 ul").css({"left":"-110px"});
	jQuery("#menu-649-1").hover(function(){
		jQuery("#menu-896-1 ul").css({"left":"-200px"});
		jQuery("#menu-897-1 ul").css({"left":"-318px"});
	});

	jQuery(".search-advanced .form-type-checkboxes").remove();
	
	/*jQuery(".page-financials li.sub_menu_level_3").click(function(){
		alert("tst");
	});*/
	
	//alert(jQuery(".page-financials li.sub_menu_level_3").text());
	var chkFinancial = jQuery(".page-financials li.sub_menu_level_3").text();
	if(chkFinancial != ""){
		window.location.href = "press-releases-list";
	}
	
	jQuery(".breadcrumb a:last").attr({"href":"#","style":"cursor:default;"});
	
	jQuery(".view-customer-care-package .ui-accordion-content").each(function(){
		//alert(jQuery(this).find(".views-field-field-ccp-logo").html());
		if(jQuery(this).find(".views-field-field-ccp-logo").html() == null){
			jQuery(this).find(".views-field-body").width("100%");
		}
	});	 
	
	
	jQuery(".page-journals .views-field-field-journal-attchmnt a,.page-journals .views-field-field-milestone-attachment a").html("&nbsp;");
	
	
	jQuery("#menu-949-1 ul").remove();
	
	/** Investors --> Stock Ticker
		Date Created: 07.11.2011 */
			
	var getCurrentPage = window.location.pathname;
	var getPath = getCurrentPage.split('/');
	if(getPath[2] == 'stock-ticker')
	{
		var refreshId = setInterval(function() { 
		
			//window.location.href = Drupal.settings.basePath+'stock-ticker';  
			window.location.href = Drupal.settings.baseURL + '/stock-ticker';
		}, 180000);
	}	
	
	jQuery('.six_months_graph').hide();
	//jQuery('.one_day').addClass("active");
	//jQuery('.six_months').removeClass("active");
	
	jQuery(".one_day").click(function(){
		jQuery('.one_day_graph').show();
		jQuery('.one_day').addClass("active");
		
		jQuery('.six_months').removeClass("active");
		jQuery('.six_months_graph').hide();		
	});
	
	jQuery(".six_months").click(function(){
		jQuery('.one_day_graph').hide();
		jQuery('.one_day').removeClass("active");
		
		jQuery('.six_months').addClass("active");
		jQuery('.six_months_graph').show();				
	});

	jQuery(".stock_refresh").click(function(){
		//alert(Drupal.settings.basePath);
		//window.location.href = Drupal.settings.basePath+'stock-ticker';
		window.location.href = Drupal.settings.baseURL + '/stock-ticker';
	});
	
	
	jQuery("#india_main_address,#regional_address,#area_address").change(function(){
		var optionVal = jQuery(this).val();
		if(optionVal == "")
			return false;
		jQuery(".address_tbl,.address_select").hide();
		jQuery("#"+jQuery(this).attr("id")).show();
		jQuery("#"+optionVal).show();
	});
	
	
	
	/** End --> Stock Ticker */
	
	/** Non Flash Version */

/*
		jQuery(".block1").nonFlashStyle({defaultLeft:'-80px', defaultTop:'-35px', animLeft:'-65px', animTop:'-25px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block2").nonFlashStyle({defaultLeft:'-50px', defaultTop:'-70px', animLeft:'-55px', animTop:'-65px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block3").nonFlashStyle({defaultLeft:'-40px', defaultTop:'-28px', animLeft:'-38px', animTop:'-25px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block4").nonFlashStyle({defaultLeft:'-27px', defaultTop:'-75px', animLeft:'-50px', animTop:'-57px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block5").nonFlashStyle({defaultLeft:'-100px', defaultTop:'-34px', animLeft:'-90px', animTop:'-24px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block6").nonFlashStyle({defaultLeft:'-27px', defaultTop:'-17px', animLeft:'-37px', animTop:'-22px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});	
		jQuery(".block7").nonFlashStyle({defaultLeft:'-27px', defaultTop:'-37px', animLeft:'-37px', animTop:'-12px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});	
		jQuery(".block8").nonFlashStyle({defaultLeft:'-27px', defaultTop:'-40px', animLeft:'-37px', animTop:'-35px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});	
		jQuery(".block9").nonFlashStyle({defaultLeft:'-27px', defaultTop:'-104px', animLeft:'-12px', animTop:'-115px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block10").nonFlashStyle({defaultLeft:'-54px', defaultTop:'-59px', animLeft:'-45px', animTop:'-72px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		jQuery(".block11").nonFlashStyle({defaultLeft:'-21px', defaultTop:'-39px', animLeft:'-15px', animTop:'-30px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});		
		jQuery(".block12").nonFlashStyle({defaultLeft:'-75px', defaultTop:'-12px', animLeft:'-65px', animTop:'-7px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});		
		jQuery(".block13").nonFlashStyle({defaultLeft:'-42px', defaultTop:'-52px', animLeft:'-32px', animTop:'-45px', opacity:'.6',imgAnimSpeed:100,overlaySpeed:200,});
		if(jQuery("#non_flash").html() != null){
			jQuery("#superfish-1").attr({'style':'margin-left:0'});
			jQuery(".sf-menu.sf-style-default a").attr({'style':'padding: 13px 7px;'});
			jQuery(".sf-style-default").attr({'style':'float:right'});
			jQuery(".header,.footer").attr({'style':'width:104%'});
		}*/
	
}
};

	function openCustomLightBox(thisObj, hrefVal){
	
			var idVal = jQuery(thisObj).attr("id");
			//alert(idVal);
			if(idVal=="write_us"){
				var contentWidth = 680;
				var contentHeight = 600;
			}
			else if(idVal == "filterYear") 
			{
				var contentWidth = 970;
				var contentHeight = 300;				
			}
			else if(idVal.indexOf("productModelNodeId") != -1 || idVal == "edit-product-search-level2" || idVal == "edit-product-search-level3-truck"){
				var contentWidth = 633;
				var contentHeight = 550;				
			}
			else{
				var contentWidth = 500;
				var contentHeight = 400;
      		}
			
			var browserWidth = (jQuery(window).width() > jQuery(document).width()) ? jQuery(window).width() : jQuery(document).width();	
			var browserHeight = (jQuery(window).height() > jQuery(document).height()) ? jQuery(window).height() : jQuery(document).height();	
			var browserWidth = jQuery(window).width();	
			var browserHeight = jQuery(window).height();	

			var contentLeft = (browserWidth - contentWidth) / 2;
			var contentTop = (browserHeight - contentHeight) / 2;
			var closeTop = contentTop + 10;
			var closeLeft = contentLeft + contentWidth - 60;
			var contentBg = 'url("'+loadingImg+'") no-repeat scroll center center #ECECEC';
			
			jQuery(".customlightbox-content,.customlightbox-overlay").remove();
			jQuery(".wrapper").after("<div class='customlightbox-overlay' style=''></div>");
			jQuery(".customlightbox-overlay").css({'position':'fixed','width':'100%','height':'100%','top':0,'left':0,'background-color':'#000','z-index':3000});
			                              
			
			 //jQuery('.customlightbox-overlay').after("<img src='"+closeImg+"' class='customlightbox-close' style='display:none'><div class='customlightbox-content'></div>"); 
    		jQuery('.customlightbox-overlay').after("<div class='customlightbox-content'></div>"); 
			                              
			jQuery(".customlightbox-content").css({'position':'fixed','width':contentWidth,'height':contentHeight,'top':contentTop,'left':contentLeft,'background':contentBg,'z-index':3022});
			//jQuery(".customlightbox-close").css({'position':'fixed','top':closeTop,'left':closeLeft,'z-index':35,'cursor':'pointer'});
			if(navigator.appVersion.indexOf("MSIE 7") != -1) {
					jQuery(".customlightbox-content").css({'top':'10%'});
			}
			jQuery('.customlightbox-overlay').stop().animate({opacity: '.8'},300,function(){
				jQuery(".customlightbox-content,.customlightbox-close").fadeIn();
			});		
			                              
			var data = '<iframe id="lightbox_frame" src="'+hrefVal+'?ajax=1" frameborder="0" width="100%" height="100%" allowtransparency="true" />';
			jQuery(".customlightbox-content").html("<img src='"+closeImg+"' class='customlightbox-close' style='display:none'>"+data);
			jQuery(".customlightbox-close").css({'z-index':35,'cursor':'pointer','float':'right','margin-top':'15px','margin-right':'15px'});
			jQuery(".header").css({'z-index':0});
			//alert(hrefVal);
			
			/* jQuery.ajax({
                  url:""+hrefVal+"?ajax=1",
				  //url:"/leadership-team-member/64?ajax=1";
                  type: "get",
                  cache:true,
                  cacheResponse:true,
                  success: function(data){
				  	jQuery(".customlightbox-content").css({'background-image':'none'}).html(data);
				 // alert(data);
                    //$(".views-row-1").html(data);
                  }
				 
				  
  			});*/
			
			//jQuery
				
			 jQuery(".customlightbox-close").click(closeCustomLightbox);
			//url("../images/inner_menu_active.gif") no-repeat scroll left center #0867A8

			//jQuery("")
			//alert(jQuery(this).attr("href"));
			
			return false;		
	}


	function customAccExpandCollapse(optVal,accHeaderCls,accContentCls){
		if(optVal == 'expand'){
			//setTimeout("setAccHeight('"+accContentCls+"')",500);	
			jQuery(accContentCls).slideDown();
			jQuery(accContentCls).addClass("ui-accordion-content-active");
			jQuery(accHeaderCls).addClass("ui-state-active ui-corner-top");
			//jQuery(accHeaderCls).attr({"aria-expanded":"true"});
			jQuery(accHeaderCls).removeClass("ui-state-default");
			jQuery(accHeaderCls).removeClass("ui-corner-all");
			jQuery(accHeaderCls).find(".ui-icon").removeClass("ui-icon-triangle-1-e");
			jQuery(accHeaderCls).find(".ui-icon").addClass("ui-icon-triangle-1-s");
			return false;
		}else{
			//jQuery(accContentCls).css("height", "auto");
			//jQuery(accContentCls).attr({"aria-expanded":"false"});
			jQuery(accContentCls).slideUp();
			jQuery(accHeaderCls).removeClass("ui-state-active");
			jQuery(accHeaderCls).removeClass("ui-corner-top");
			jQuery(accHeaderCls).addClass("ui-state-default ui-corner-all");
			jQuery(accHeaderCls).find(".ui-icon").addClass("ui-icon-triangle-1-e");
			jQuery(accHeaderCls).find(".ui-icon").removeClass("ui-icon-triangle-1-s");
			return false;			
		}
	}
	
	function setAccHeight(thisOption){
			jQuery(thisOption).css("height", "500px");		
	}
	function jointVentureSetHeight(){
		setJointVentureHeight();
	}
	
	function setJointVentureHeight(){
		jQuery(".view-id-joint_ventures .view-content .views-row").each(function(){
		var panelHeight = "";
		panelHeight = jQuery(this).height();
		var imageHeight;
		imageHeight = jQuery(this).find(".views-field-field-jv-image").height();
		var diffHeight;
		diffHeight = panelHeight-imageHeight;
		jQuery(this).find(".views-field-field-jv-image").css({"margin-top":diffHeight});
		
		/*jQuery(this).find(".views-field-field-jv-image").animate({
				   		marginTop: diffHeight
					}, 0, function() {
					});*/
		
		});
	}
	
	
	
	function closeCustomLightbox(){
		jQuery(".customlightbox-content").html('');
		jQuery('.customlightbox-overlay,.customlightbox-close,.customlightbox-content').fadeOut(300, function() {
    		jQuery(this).remove()
  		});
		jQuery(".header").css({'z-index':2});
		jQuery("html").css({"overflow":"auto"});
		
	}
	
	function customAjax(ajaxUrl){
	//alert("tast");
	//url("../images/inner_menu_active.gif") no-repeat scroll left center #0867A8
			var loadingBg = 'url("'+loadingImg+'") no-repeat scroll center 45% #000';
			//jQuery(".page_middle_content").css({'background':loadingBg,'min-height':400});
			jQuery(".loaderOverlay").remove();
			jQuery(".page_middle_content").before("<div class='loaderOverlay'></div>");
			jQuery(".loaderOverlay").css({'position':'fixed','z-index':3000,'background':loadingBg,'width':'100%','height':'100%','left':0,'top':0});
			var appendStr;
			                      if(ajaxUrl.indexOf("?")==-1){
			                      appendStr = "?";
                            }else{
                            appendStr = "&";
                            }
						                      
			var processedURL = ""+ajaxUrl+appendStr+"ajax=2";
			jQuery('.loaderOverlay').stop().animate({opacity: '.7'},300,function(){});				
			//return false;
			
			
			//alert("sta");
			var data ="";
			var data = '<iframe id="customIframe" src="'+ajaxUrl+'?ajax=2" frameborder="0" width="99%" height=""  frameborder="no" style="overflow:hidden;min-height:830px;" allowtransparency="true" />';
			
			//alert(data);
			
			jQuery(".page_middle_content").html(data);
			
			
			
			// jQuery(".loaderOverlay").remove();
	/*		
		jQuery.ajax({
                  url:processedURL,
				  //url:"/leadership-team-member/64?ajax=1";
                  type: "get",
                  dataType: "html",
                  cache:true,
                  cacheResponse:true,
                  success: function(data){
					//jQuery('.page_middle_content').stop().animate({opacity: '1'},300,function(){});	
				  	//jQuery(".page_middle_content").css({'background-image':'none'}).html(data);
         			//jQuery(".page_middle_content").html( jQuery(".page_tpl_right_top,.page_tpl_right_bottom",data));
          			jQuery(".page_middle_content").html(data);
					//alert("tsat");
                   // alert(cajaxUrl);
				   
					//jQuery(".loaderOverlay").fadeOut(100,function(){
					//	jQuery(this).remove();
					//});
					//alert('inn');
					//alert(ajaxUrl.indexOf("manufacturing-facilities"));
					//alert(Drupal.settings.views_accordion);
					
					Drupal.attachBehaviors(jQuery(".page_middle_content"));		
					//alert('innn');
					//Drupal.settings.views_accordion(jQuery(".page_middle_content"));
					jQuery(".loaderOverlay").remove();
					//Drupal.settings.views_accordion(jQuery(".page_middle_content"));
					//alert('i am in');
					if(ajaxUrl.indexOf("manufacturing-facilities") != -1){
						jQuery('a[href="'+ajaxUrl+'"]').find('img').css({'border':'2px solid #027FBE'});
				  }
				  
      if(ajaxUrl.indexOf("current-openings") != -1){
        jQuery('a[href="'+ajaxHrefVal+'"]').parent().parent().parent().css({'background-color':'#ccc'});
      }
      if(ajaxUrl.indexOf("direct-entry") != -1){
        jQuery('a[href="'+ajaxHrefVal+'"]').parent().parent().parent().css({'background-color':'#ccc'});
      }
      if(ajaxUrl.indexOf("graduate-trainees") != -1){
        jQuery('a[href="'+ajaxHrefVal+'"]').parent().parent().parent().css({'background-color':'#ccc'});
      }
      if(ajaxUrl.indexOf("sabbatical") != -1){
        jQuery('a[href="'+ajaxHrefVal+'"]').parent().parent().parent().css({'background-color':'#ccc'});
      }
	   if(ajaxUrl.indexOf("presentations") != -1){
        jQuery('a[href="'+ajaxHrefVal+'"]').parent().parent().parent().css({'background-color':'#ccc'});
      }
      
				  
						//alert(jQuery('a[href="'+highLightUrl+'"]').html());
                  }
  			});*/		
			return false;
	}
	
	
	function centerBgTransparent(){
		browserHeight = (jQuery(window).height() > jQuery(document).height()) ? jQuery(window).height() : jQuery(document).height();		
		browserHeight = browserHeight - 30;
		jQuery(".center_bg_transparent").attr({"height":browserHeight});		
		setTimeout("centerBgTransparent()",1000);
		//alert(browserHeight);
	}

/*jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
    	wrap: 'circular',
		scroll:1
    });
	var current=1;
	 jQuery('.jcarousel-next').click(function(){
		if(current==-1) return false;
		jQuery('.history-slider-menu ul li a').eq(current%jQuery('.history-slider-menu ul li a').length).trigger('click',[true]);	// [true] will be passed as the keepScroll parameter of the click function on line 28
		current++; 
	 })
});*/


/*jQuery(document).ready(function(){
jQuery(".page-article-163 .content .view-dom-id-2").append("<div class='apply_now_btn'><a href='"+baseUrl+"/article/206'>Apply Now</a></div>");
  jQuery(".page-article-187 .content .view-dom-id-1").append("<div class='apply_now_btn'><a href='"+baseUrl+"/article/206'>Apply Now</a></div>");
  jQuery(".page-article-189 .content .view-dom-id-1").append("<div class='apply_now_btn'><a href='"+baseUrl+"/article/206'>Apply Now</a></div>");  
});*/

function loadThisFilter(cntrl, currURL) {
	//alert(currURL);
	//customAjax(ajaxUrl)
	//window.location.href = Drupal.settings.basePath+currURL+'/'+cntrl.value;
	window.location.href = Drupal.settings.baseURL+'/'+currURL+'/'+cntrl.value;
	
	//customAjax(currURL+'/'+cntrl.value);
}

function loadThisFilter_salesUpdates(cntrl, currURL) {
	//alert(currURL);
	//customAjax(ajaxUrl)
	var currentDate = new Date();
	var year = currentDate.getFullYear();
	
	/*if(cntrl.value == (year - 1)) {
		
		//window.location.href = Drupal.settings.basePath+currURL+'/'+cntrl.value;
		window.location.href = Drupal.settings.baseURL+'/'+currURL+'/'+cntrl.value;	
	}*/
	/*else	
	{*/
		//var hrefVal = Drupal.settings.basePath+currURL+'/'+cntrl.value; //jQuery(this).attr("href");
		var hrefVal = Drupal.settings.baseURL+'/'+currURL+'/'+cntrl.value;
		if(hrefVal == '#'){
				return false;
		}
			//alert(idVal);
		openCustomLightBox(cntrl, hrefVal);
		//openCustomLightBox(hrefVal,idVal);
		return false;
	/*}*/
	//customAjax(currURL+'/'+cntrl.value);
}

function loadPressRelease(cntrl, currURL) {
	//alert(jQuery("#press-release-year").val()); 
	//alert(currURL);
	//customAjax(ajaxUrl)
	var yearVal = jQuery("#press-release-year").val();
	// window.location.href = Drupal.settings.basePath+currURL+'/'+yearVal+'/'+cntrl.value;
	window.location.href = Drupal.settings.baseURL+'/'+currURL+'/'+yearVal+'/'+cntrl.value;
	//customAjax(currURL+'/'+cntrl.value);
}

function ourWorldCompanies(){
	var panelHeight;
	var imageHeight;
	var diffHeight;
	jQuery(".view-id-joint_ventures .view-content > div").each(function(){
		panelHeight = jQuery(this).height();
		imageHeight = jQuery(this).find(".views-field-field-jv-image").height();
		diffHeight = panelHeight-imageHeight;
		
		if(diffHeight > 100)
			jQuery(this).find(".views-field-field-jv-image").css({"margin-top":diffHeight/4});
	});
}

function getLatestStockDetails() {
	//alert('innn');
	customAjax('stock-ticker');
}

function conferenceCallRedirect(getId){
	if(getId == 'agree'){
		jQuery(".conference-call-document-block").show();
		jQuery("#block-investors-conference-call-transcripts").hide();
		
		getConfCallPeriod();
	}
	else
		window.location.href = Drupal.settings.baseURL+'/';
}

/** Conference Call Transcript Archive 
	Date Created: 02.11.2011  
*/

function getConfCallPeriod() {
	
	var getYear = jQuery(".page-article-1017 .page_tpl_right .page_tpl_right_middle .view-content h3 .date-display-start").text();	
	var strLength = getYear.length;
	var noOfYears = strLength/4;
		
	//var createDiv = document.createElement('div');
	//createDiv.setAttribute("id", "year_archive");
	//createDiv.setAttribute("class", "share_holder_archive_lable");
	
	/*var createSelect = document.createElement('select');
	createSelect.setAttribute("id", 'cct_year_archive');
	createSelect.setAttribute("name", 'cct_year_archive');
	createSelect.setAttribute("clas", 'form-select');
	//createSelect.setAttribute("style", 'position: absolute; height: 24px; opacity: 0; font-size: 13px;');
	createSelect.setAttribute("onchange", 'archiveConfCallPeriod(this.value, '+noOfYears+')');*/
	
	var j=0;
	for (i=0; i< strLength; i=i+4)
	{
		var fromYear = getYear.slice(i, i+4);
		var toYear = parseInt(fromYear) + 1;
		
		var createOption = document.createElement("option");
		createOption.value = j; 
		createOption.text = fromYear+' - '+ toYear;  

		jQuery('#cct_filterYear').get(0)[jQuery('#cct_filterYear option').length] = createOption;
		
		//cct_filterYear.appendChild(createOption);		
		j++;
		
		jQuery(".view-id-conference_call_transcripts h3:eq("+j+")").hide();
		jQuery(".view-id-conference_call_transcripts h3:eq("+j+")").nextAll().hide();
	}

 	/**Conference Call Transcript */
	
	
	//jQuery('.page-article-1017 .page_tpl_right_middle .content').prepend(jQuery(createSelect));
	//jQuery('.page-article-1017 .page_tpl_right_middle .content').prepend(jQuery(createDiv));
		
	//jQuery('div #year_archive').text('Archives');
	jQuery(".form-select").customSelectBoxStyle();
}

function archiveConfCallPeriod(thisObj)
{	
	var val = thisObj.value;
	var noOfYears = thisObj.length;
	for (var i=0; i< noOfYears; i++)
	{
		if(i != val)
		{
			jQuery(".view-id-conference_call_transcripts h3:eq("+i+")").hide();
			jQuery(".view-id-conference_call_transcripts h3:eq("+i+")").nextAll().hide();
		}	
		else
		{
			jQuery(".view-id-conference_call_transcripts h3:eq("+i+")").show();
			jQuery(".view-id-conference_call_transcripts h3:eq("+i+")").nextAll().show();
		}
	}
}

function removeProductTitleLink(){
//alert("test");
	
	//alert(jQuery("#customIframe").contents().find(".view-product-details .node-products h2.node-title a").text());
	
	/*var productTitle = jQuery("#customIframe").contents().find(".view-product-details .node-products h2.node-title a").text();
	alert(productTitle);
	alert(jQuery(".view-product-details .node-products h2.node-title a").text());
	jQuery("#customIframe").contents().find(".view-product-details .node-products h2.node-title").text(productTitle);*/
	
	/*var trcukProductTitle = jQuery(".page-product-details .page_tpl_right_bottom #block-system-main .view-product-details .node-truck-products h2.node-title a").text();
	jQuery(".page-product-details .page_tpl_right_bottom #block-system-main .view-product-details .node-truck-products h2.node-title").text(trcukProductTitle);*/
}


/* Mobile Version */
/*
	(function($){
		$.fn.extend({
	 	nonFlashStyle : function(options) {
		var defaultLeft = options.defaultLeft;
		var defaultTop = options.defaultTop;
		var animLeft = options.animLeft;
		var animTop = options.animTop;
		var opacity = options.opacity;
		var imgAnimSpeed = options.imgAnimSpeed;
		var overlaySpeed = options.overlaySpeed;
		 	jQuery(this).mouseenter(function(e) {
	            jQuery(this).children('a').children('img').animate({  left: animLeft, top: animTop}, imgAnimSpeed);
				jQuery(this).children('a').children('span').animate({opacity: opacity},100,function(){
					jQuery(this).fadeIn(overlaySpeed);
					jQuery(this).next("p").show();
				});
	        }).mouseleave(function(e) {
	            jQuery(this).children('a').children('img').animate({  left: defaultLeft, top: defaultTop}, imgAnimSpeed);
	           	jQuery(this).children('a').children('span').animate({opacity: opacity},100,function(){
					jQuery(this).fadeOut(overlaySpeed);
					jQuery(this).next("p").hide();
				});
	        });
		}
	 	});
	})(jQuery)*/;
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.4
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    
    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }
    
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    
    return $.event.handle.apply(this, args);
}

})(jQuery);;
/*!
 * jScrollPane - v2.0.0beta11 - 2011-06-11
 * http://jscrollpane.kelvinluck.com/
 *
 * Copyright (c) 2010 Kelvin Luck
 * Dual licensed under the MIT and GPL licenses.
 */

// Script: jScrollPane - cross browser customisable scrollbars
//
// *Version: 2.0.0beta11, Last updated: 2011-06-11*
//
// Project Home - http://jscrollpane.kelvinluck.com/
// GitHub       - http://github.com/vitch/jScrollPane
// Source       - http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.js
// (Minified)   - http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.min.js
//
// About: License
//
// Copyright (c) 2011 Kelvin Luck
// Dual licensed under the MIT or GPL Version 2 licenses.
// http://jscrollpane.kelvinluck.com/MIT-LICENSE.txt
// http://jscrollpane.kelvinluck.com/GPL-LICENSE.txt
//
// About: Examples
//
// All examples and demos are available through the jScrollPane example site at:
// http://jscrollpane.kelvinluck.com/
//
// About: Support and Testing
//
// This plugin is tested on the browsers below and has been found to work reliably on them. If you run
// into a problem on one of the supported browsers then please visit the support section on the jScrollPane
// website (http://jscrollpane.kelvinluck.com/) for more information on getting support. You are also
// welcome to fork the project on GitHub if you can contribute a fix for a given issue. 
//
// jQuery Versions - tested in 1.4.2+ - reported to work in 1.3.x
// Browsers Tested - Firefox 3.6.8, Safari 5, Opera 10.6, Chrome 5.0, IE 6, 7, 8
//
// About: Release History
//
// 2.0.0beta11 - (in progress) 
// 2.0.0beta10 - (2011-04-17) cleaner required size calculation, improved keyboard support, stickToBottom/Left, other small fixes
// 2.0.0beta9 - (2011-01-31) new API methods, bug fixes and correct keyboard support for FF/OSX
// 2.0.0beta8 - (2011-01-29) touchscreen support, improved keyboard support
// 2.0.0beta7 - (2011-01-23) scroll speed consistent (thanks Aivo Paas)
// 2.0.0beta6 - (2010-12-07) scrollToElement horizontal support
// 2.0.0beta5 - (2010-10-18) jQuery 1.4.3 support, various bug fixes
// 2.0.0beta4 - (2010-09-17) clickOnTrack support, bug fixes
// 2.0.0beta3 - (2010-08-27) Horizontal mousewheel, mwheelIntent, keyboard support, bug fixes
// 2.0.0beta2 - (2010-08-21) Bug fixes
// 2.0.0beta1 - (2010-08-17) Rewrite to follow modern best practices and enable horizontal scrolling, initially hidden
//							 elements and dynamically sized elements.
// 1.x - (2006-12-31 - 2010-07-31) Initial version, hosted at googlecode, deprecated

(function($,window,undefined){

	$.fn.jScrollPane = function(settings)
	{
		// JScrollPane "class" - public methods are available through $('selector').data('jsp')
		function JScrollPane(elem, s)
		{
			var settings, jsp = this, pane, paneWidth, paneHeight, container, contentWidth, contentHeight,
				percentInViewH, percentInViewV, isScrollableV, isScrollableH, verticalDrag, dragMaxY,
				verticalDragPosition, horizontalDrag, dragMaxX, horizontalDragPosition,
				verticalBar, verticalTrack, scrollbarWidth, verticalTrackHeight, verticalDragHeight, arrowUp, arrowDown,
				horizontalBar, horizontalTrack, horizontalTrackWidth, horizontalDragWidth, arrowLeft, arrowRight,
				reinitialiseInterval, originalPadding, originalPaddingTotalWidth, previousContentWidth,
				wasAtTop = true, wasAtLeft = true, wasAtBottom = false, wasAtRight = false,
				originalElement = elem.clone(false, false).empty(),
				mwEvent = $.fn.mwheelIntent ? 'mwheelIntent.jsp' : 'mousewheel.jsp';

			originalPadding = elem.css('paddingTop') + ' ' +
								elem.css('paddingRight') + ' ' +
								elem.css('paddingBottom') + ' ' +
								elem.css('paddingLeft');
			originalPaddingTotalWidth = (parseInt(elem.css('paddingLeft'), 10) || 0) +
										(parseInt(elem.css('paddingRight'), 10) || 0);

			function initialise(s)
			{

				var /*firstChild, lastChild, */isMaintainingPositon, lastContentX, lastContentY,
						hasContainingSpaceChanged, originalScrollTop, originalScrollLeft,
						maintainAtBottom = false, maintainAtRight = false;

				settings = s;

				if (pane === undefined) {
					originalScrollTop = elem.scrollTop();
					originalScrollLeft = elem.scrollLeft();

					elem.css(
						{
							overflow: 'hidden',
							padding: 0
						}
					);
					// TODO: Deal with where width/ height is 0 as it probably means the element is hidden and we should
					// come back to it later and check once it is unhidden...
					paneWidth = elem.innerWidth() + originalPaddingTotalWidth;
					paneHeight = elem.innerHeight();

					elem.width(paneWidth);
					
					pane = $('<div class="jspPane" />').css('padding', originalPadding).append(elem.children());
					container = $('<div class="jspContainer" />')
						.css({
							'width': paneWidth + 'px',
							'height': paneHeight + 'px'
						}
					).append(pane).appendTo(elem);

					/*
					// Move any margins from the first and last children up to the container so they can still
					// collapse with neighbouring elements as they would before jScrollPane 
					firstChild = pane.find(':first-child');
					lastChild = pane.find(':last-child');
					elem.css(
						{
							'margin-top': firstChild.css('margin-top'),
							'margin-bottom': lastChild.css('margin-bottom')
						}
					);
					firstChild.css('margin-top', 0);
					lastChild.css('margin-bottom', 0);
					*/
				} else {
					elem.css('width', '');

					maintainAtBottom = settings.stickToBottom && isCloseToBottom();
					maintainAtRight  = settings.stickToRight  && isCloseToRight();

					hasContainingSpaceChanged = elem.innerWidth() + originalPaddingTotalWidth != paneWidth || elem.outerHeight() != paneHeight;

					if (hasContainingSpaceChanged) {
						paneWidth = elem.innerWidth() + originalPaddingTotalWidth;
						paneHeight = elem.innerHeight();
						container.css({
							width: paneWidth + 'px',
							height: paneHeight + 'px'
						});
					}

					// If nothing changed since last check...
					if (!hasContainingSpaceChanged && previousContentWidth == contentWidth && pane.outerHeight() == contentHeight) {
						elem.width(paneWidth);
						return;
					}
					previousContentWidth = contentWidth;
					
					pane.css('width', '');
					elem.width(paneWidth);

					container.find('>.jspVerticalBar,>.jspHorizontalBar').remove().end();
				}

				pane.css('overflow', 'auto');
				if (s.contentWidth) {
					contentWidth = s.contentWidth;
				} else {
					contentWidth = pane[0].scrollWidth;
				}
				contentHeight = pane[0].scrollHeight;
				pane.css('overflow', '');

				percentInViewH = contentWidth / paneWidth;
				percentInViewV = contentHeight / paneHeight;
				isScrollableV = percentInViewV > 1;

				isScrollableH = percentInViewH > 1;

				//console.log(paneWidth, paneHeight, contentWidth, contentHeight, percentInViewH, percentInViewV, isScrollableH, isScrollableV);

				if (!(isScrollableH || isScrollableV)) {
					elem.removeClass('jspScrollable');
					pane.css({
						top: 0,
						width: container.width() - originalPaddingTotalWidth
					});
					removeMousewheel();
					removeFocusHandler();
					removeKeyboardNav();
					removeClickOnTrack();
					unhijackInternalLinks();
				} else {
					elem.addClass('jspScrollable');

					isMaintainingPositon = settings.maintainPosition && (verticalDragPosition || horizontalDragPosition);
					if (isMaintainingPositon) {
						lastContentX = contentPositionX();
						lastContentY = contentPositionY();
					}

					initialiseVerticalScroll();
					initialiseHorizontalScroll();
					resizeScrollbars();

					if (isMaintainingPositon) {
						scrollToX(maintainAtRight  ? (contentWidth  - paneWidth ) : lastContentX, false);
						scrollToY(maintainAtBottom ? (contentHeight - paneHeight) : lastContentY, false);
					}

					initFocusHandler();
					initMousewheel();
					initTouch();
					
					if (settings.enableKeyboardNavigation) {
						initKeyboardNav();
					}
					if (settings.clickOnTrack) {
						initClickOnTrack();
					}
					
					observeHash();
					if (settings.hijackInternalLinks) {
						hijackInternalLinks();
					}
				}

				if (settings.autoReinitialise && !reinitialiseInterval) {
					reinitialiseInterval = setInterval(
						function()
						{
							initialise(settings);
						},
						settings.autoReinitialiseDelay
					);
				} else if (!settings.autoReinitialise && reinitialiseInterval) {
					clearInterval(reinitialiseInterval);
				}

				originalScrollTop && elem.scrollTop(0) && scrollToY(originalScrollTop, false);
				originalScrollLeft && elem.scrollLeft(0) && scrollToX(originalScrollLeft, false);

				elem.trigger('jsp-initialised', [isScrollableH || isScrollableV]);
			}

			function initialiseVerticalScroll()
			{
				if (isScrollableV) {

					container.append(
						$('<div class="jspVerticalBar" />').append(
							$('<div class="jspCap jspCapTop" />'),
							$('<div class="jspTrack" />').append(
								$('<div class="jspDrag" />').append(
									$('<div class="jspDragTop" />'),
									$('<div class="jspDragBottom" />')
								)
							),
							$('<div class="jspCap jspCapBottom" />')
						)
					);

					verticalBar = container.find('>.jspVerticalBar');
					verticalTrack = verticalBar.find('>.jspTrack');
					verticalDrag = verticalTrack.find('>.jspDrag');

					if (settings.showArrows) {
						arrowUp = $('<a class="jspArrow jspArrowUp" />').bind(
							'mousedown.jsp', getArrowScroll(0, -1)
						).bind('click.jsp', nil);
						arrowDown = $('<a class="jspArrow jspArrowDown" />').bind(
							'mousedown.jsp', getArrowScroll(0, 1)
						).bind('click.jsp', nil);
						if (settings.arrowScrollOnHover) {
							arrowUp.bind('mouseover.jsp', getArrowScroll(0, -1, arrowUp));
							arrowDown.bind('mouseover.jsp', getArrowScroll(0, 1, arrowDown));
						}

						appendArrows(verticalTrack, settings.verticalArrowPositions, arrowUp, arrowDown);
					}

					verticalTrackHeight = paneHeight;
					container.find('>.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow').each(
						function()
						{
							verticalTrackHeight -= $(this).outerHeight();
						}
					);


					verticalDrag.hover(
						function()
						{
							verticalDrag.addClass('jspHover');
						},
						function()
						{
							verticalDrag.removeClass('jspHover');
						}
					).bind(
						'mousedown.jsp',
						function(e)
						{
							// Stop IE from allowing text selection
							$('html').bind('dragstart.jsp selectstart.jsp', nil);

							verticalDrag.addClass('jspActive');

							var startY = e.pageY - verticalDrag.position().top;

							$('html').bind(
								'mousemove.jsp',
								function(e)
								{
									positionDragY(e.pageY - startY, false);
								}
							).bind('mouseup.jsp mouseleave.jsp', cancelDrag);
							return false;
						}
					);
					sizeVerticalScrollbar();
				}
			}

			function sizeVerticalScrollbar()
			{
				verticalTrack.height(verticalTrackHeight + 'px');
				verticalDragPosition = 0;
				scrollbarWidth = settings.verticalGutter + verticalTrack.outerWidth();

				// Make the pane thinner to allow for the vertical scrollbar
				pane.width(paneWidth - scrollbarWidth - originalPaddingTotalWidth);

				// Add margin to the left of the pane if scrollbars are on that side (to position
				// the scrollbar on the left or right set it's left or right property in CSS)
				try {
					if (verticalBar.position().left === 0) {
						pane.css('margin-left', scrollbarWidth + 'px');
					}
				} catch (err) {
				}
			}

			function initialiseHorizontalScroll()
			{
				if (isScrollableH) {

					container.append(
						$('<div class="jspHorizontalBar" />').append(
							$('<div class="jspCap jspCapLeft" />'),
							$('<div class="jspTrack" />').append(
								$('<div class="jspDrag" />').append(
									$('<div class="jspDragLeft" />'),
									$('<div class="jspDragRight" />')
								)
							),
							$('<div class="jspCap jspCapRight" />')
						)
					);

					horizontalBar = container.find('>.jspHorizontalBar');
					horizontalTrack = horizontalBar.find('>.jspTrack');
					horizontalDrag = horizontalTrack.find('>.jspDrag');

					if (settings.showArrows) {
						arrowLeft = $('<a class="jspArrow jspArrowLeft" />').bind(
							'mousedown.jsp', getArrowScroll(-1, 0)
						).bind('click.jsp', nil);
						arrowRight = $('<a class="jspArrow jspArrowRight" />').bind(
							'mousedown.jsp', getArrowScroll(1, 0)
						).bind('click.jsp', nil);
						if (settings.arrowScrollOnHover) {
							arrowLeft.bind('mouseover.jsp', getArrowScroll(-1, 0, arrowLeft));
							arrowRight.bind('mouseover.jsp', getArrowScroll(1, 0, arrowRight));
						}
						appendArrows(horizontalTrack, settings.horizontalArrowPositions, arrowLeft, arrowRight);
					}

					horizontalDrag.hover(
						function()
						{
							horizontalDrag.addClass('jspHover');
						},
						function()
						{
							horizontalDrag.removeClass('jspHover');
						}
					).bind(
						'mousedown.jsp',
						function(e)
						{
							// Stop IE from allowing text selection
							$('html').bind('dragstart.jsp selectstart.jsp', nil);

							horizontalDrag.addClass('jspActive');

							var startX = e.pageX - horizontalDrag.position().left;

							$('html').bind(
								'mousemove.jsp',
								function(e)
								{
									positionDragX(e.pageX - startX, false);
								}
							).bind('mouseup.jsp mouseleave.jsp', cancelDrag);
							return false;
						}
					);
					horizontalTrackWidth = container.innerWidth();
					sizeHorizontalScrollbar();
				}
			}

			function sizeHorizontalScrollbar()
			{
				container.find('>.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow').each(
					function()
					{
						horizontalTrackWidth -= $(this).outerWidth();
					}
				);

				horizontalTrack.width(horizontalTrackWidth + 'px');
				horizontalDragPosition = 0;
			}

			function resizeScrollbars()
			{
				if (isScrollableH && isScrollableV) {
					var horizontalTrackHeight = horizontalTrack.outerHeight(),
						verticalTrackWidth = verticalTrack.outerWidth();
					verticalTrackHeight -= horizontalTrackHeight;
					$(horizontalBar).find('>.jspCap:visible,>.jspArrow').each(
						function()
						{
							horizontalTrackWidth += $(this).outerWidth();
						}
					);
					horizontalTrackWidth -= verticalTrackWidth;
					paneHeight -= verticalTrackWidth;
					paneWidth -= horizontalTrackHeight;
					horizontalTrack.parent().append(
						$('<div class="jspCorner" />').css('width', horizontalTrackHeight + 'px')
					);
					sizeVerticalScrollbar();
					sizeHorizontalScrollbar();
				}
				// reflow content
				if (isScrollableH) {
					pane.width((container.outerWidth() - originalPaddingTotalWidth) + 'px');
				}
				contentHeight = pane.outerHeight();
				percentInViewV = contentHeight / paneHeight;

				if (isScrollableH) {
					horizontalDragWidth = Math.ceil(1 / percentInViewH * horizontalTrackWidth);
					if (horizontalDragWidth > settings.horizontalDragMaxWidth) {
						horizontalDragWidth = settings.horizontalDragMaxWidth;
					} else if (horizontalDragWidth < settings.horizontalDragMinWidth) {
						horizontalDragWidth = settings.horizontalDragMinWidth;
					}
					horizontalDrag.width(horizontalDragWidth + 'px');
					dragMaxX = horizontalTrackWidth - horizontalDragWidth;
					_positionDragX(horizontalDragPosition); // To update the state for the arrow buttons
				}
				if (isScrollableV) {
					verticalDragHeight = Math.ceil(1 / percentInViewV * verticalTrackHeight);
					if (verticalDragHeight > settings.verticalDragMaxHeight) {
						verticalDragHeight = settings.verticalDragMaxHeight;
					} else if (verticalDragHeight < settings.verticalDragMinHeight) {
						verticalDragHeight = settings.verticalDragMinHeight;
					}
					verticalDrag.height(verticalDragHeight + 'px');
					dragMaxY = verticalTrackHeight - verticalDragHeight;
					_positionDragY(verticalDragPosition); // To update the state for the arrow buttons
				}
			}

			function appendArrows(ele, p, a1, a2)
			{
				var p1 = "before", p2 = "after", aTemp;
				
				// Sniff for mac... Is there a better way to determine whether the arrows would naturally appear
				// at the top or the bottom of the bar?
				if (p == "os") {
					p = /Mac/.test(navigator.platform) ? "after" : "split";
				}
				if (p == p1) {
					p2 = p;
				} else if (p == p2) {
					p1 = p;
					aTemp = a1;
					a1 = a2;
					a2 = aTemp;
				}

				ele[p1](a1)[p2](a2);
			}

			function getArrowScroll(dirX, dirY, ele)
			{
				return function()
				{
					arrowScroll(dirX, dirY, this, ele);
					this.blur();
					return false;
				};
			}

			function arrowScroll(dirX, dirY, arrow, ele)
			{
				arrow = $(arrow).addClass('jspActive');

				var eve,
					scrollTimeout,
					isFirst = true,
					doScroll = function()
					{
						if (dirX !== 0) {
							jsp.scrollByX(dirX * settings.arrowButtonSpeed);
						}
						if (dirY !== 0) {
							jsp.scrollByY(dirY * settings.arrowButtonSpeed);
						}
						scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.arrowRepeatFreq);
						isFirst = false;
					};

				doScroll();

				eve = ele ? 'mouseout.jsp' : 'mouseup.jsp';
				ele = ele || $('html');
				ele.bind(
					eve,
					function()
					{
						arrow.removeClass('jspActive');
						scrollTimeout && clearTimeout(scrollTimeout);
						scrollTimeout = null;
						ele.unbind(eve);
					}
				);
			}

			function initClickOnTrack()
			{
				removeClickOnTrack();
				if (isScrollableV) {
					verticalTrack.bind(
						'mousedown.jsp',
						function(e)
						{
							if (e.originalTarget === undefined || e.originalTarget == e.currentTarget) {
								var clickedTrack = $(this),
									offset = clickedTrack.offset(),
									direction = e.pageY - offset.top - verticalDragPosition,
									scrollTimeout,
									isFirst = true,
									doScroll = function()
									{
										var offset = clickedTrack.offset(),
											pos = e.pageY - offset.top - verticalDragHeight / 2,
											contentDragY = paneHeight * settings.scrollPagePercent,
											dragY = dragMaxY * contentDragY / (contentHeight - paneHeight);
										if (direction < 0) {
											if (verticalDragPosition - dragY > pos) {
												jsp.scrollByY(-contentDragY);
											} else {
												positionDragY(pos);
											}
										} else if (direction > 0) {
											if (verticalDragPosition + dragY < pos) {
												jsp.scrollByY(contentDragY);
											} else {
												positionDragY(pos);
											}
										} else {
											cancelClick();
											return;
										}
										scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.trackClickRepeatFreq);
										isFirst = false;
									},
									cancelClick = function()
									{
										scrollTimeout && clearTimeout(scrollTimeout);
										scrollTimeout = null;
										$(document).unbind('mouseup.jsp', cancelClick);
									};
								doScroll();
								$(document).bind('mouseup.jsp', cancelClick);
								return false;
							}
						}
					);
				}
				
				if (isScrollableH) {
					horizontalTrack.bind(
						'mousedown.jsp',
						function(e)
						{
							if (e.originalTarget === undefined || e.originalTarget == e.currentTarget) {
								var clickedTrack = $(this),
									offset = clickedTrack.offset(),
									direction = e.pageX - offset.left - horizontalDragPosition,
									scrollTimeout,
									isFirst = true,
									doScroll = function()
									{
										var offset = clickedTrack.offset(),
											pos = e.pageX - offset.left - horizontalDragWidth / 2,
											contentDragX = paneWidth * settings.scrollPagePercent,
											dragX = dragMaxX * contentDragX / (contentWidth - paneWidth);
										if (direction < 0) {
											if (horizontalDragPosition - dragX > pos) {
												jsp.scrollByX(-contentDragX);
											} else {
												positionDragX(pos);
											}
										} else if (direction > 0) {
											if (horizontalDragPosition + dragX < pos) {
												jsp.scrollByX(contentDragX);
											} else {
												positionDragX(pos);
											}
										} else {
											cancelClick();
											return;
										}
										scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.trackClickRepeatFreq);
										isFirst = false;
									},
									cancelClick = function()
									{
										scrollTimeout && clearTimeout(scrollTimeout);
										scrollTimeout = null;
										$(document).unbind('mouseup.jsp', cancelClick);
									};
								doScroll();
								$(document).bind('mouseup.jsp', cancelClick);
								return false;
							}
						}
					);
				}
			}

			function removeClickOnTrack()
			{
				if (horizontalTrack) {
					horizontalTrack.unbind('mousedown.jsp');
				}
				if (verticalTrack) {
					verticalTrack.unbind('mousedown.jsp');
				}
			}

			function cancelDrag()
			{
				$('html').unbind('dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp');

				if (verticalDrag) {
					verticalDrag.removeClass('jspActive');
				}
				if (horizontalDrag) {
					horizontalDrag.removeClass('jspActive');
				}
			}

			function positionDragY(destY, animate)
			{
				if (!isScrollableV) {
					return;
				}
				if (destY < 0) {
					destY = 0;
				} else if (destY > dragMaxY) {
					destY = dragMaxY;
				}

				// can't just check if(animate) because false is a valid value that could be passed in...
				if (animate === undefined) {
					animate = settings.animateScroll;
				}
				if (animate) {
					jsp.animate(verticalDrag, 'top', destY,	_positionDragY);
				} else {
					verticalDrag.css('top', destY);
					_positionDragY(destY);
				}

			}

			function _positionDragY(destY)
			{
				if (destY === undefined) {
					destY = verticalDrag.position().top;
				}

				container.scrollTop(0);
				verticalDragPosition = destY;

				var isAtTop = verticalDragPosition === 0,
					isAtBottom = verticalDragPosition == dragMaxY,
					percentScrolled = destY/ dragMaxY,
					destTop = -percentScrolled * (contentHeight - paneHeight);

				if (wasAtTop != isAtTop || wasAtBottom != isAtBottom) {
					wasAtTop = isAtTop;
					wasAtBottom = isAtBottom;
					elem.trigger('jsp-arrow-change', [wasAtTop, wasAtBottom, wasAtLeft, wasAtRight]);
				}
				
				updateVerticalArrows(isAtTop, isAtBottom);
				pane.css('top', destTop);
				elem.trigger('jsp-scroll-y', [-destTop, isAtTop, isAtBottom]).trigger('scroll');
			}

			function positionDragX(destX, animate)
			{
				if (!isScrollableH) {
					return;
				}
				if (destX < 0) {
					destX = 0;
				} else if (destX > dragMaxX) {
					destX = dragMaxX;
				}

				if (animate === undefined) {
					animate = settings.animateScroll;
				}
				if (animate) {
					jsp.animate(horizontalDrag, 'left', destX,	_positionDragX);
				} else {
					horizontalDrag.css('left', destX);
					_positionDragX(destX);
				}
			}

			function _positionDragX(destX)
			{
				if (destX === undefined) {
					destX = horizontalDrag.position().left;
				}

				container.scrollTop(0);
				horizontalDragPosition = destX;

				var isAtLeft = horizontalDragPosition === 0,
					isAtRight = horizontalDragPosition == dragMaxX,
					percentScrolled = destX / dragMaxX,
					destLeft = -percentScrolled * (contentWidth - paneWidth);

				if (wasAtLeft != isAtLeft || wasAtRight != isAtRight) {
					wasAtLeft = isAtLeft;
					wasAtRight = isAtRight;
					elem.trigger('jsp-arrow-change', [wasAtTop, wasAtBottom, wasAtLeft, wasAtRight]);
				}
				
				updateHorizontalArrows(isAtLeft, isAtRight);
				pane.css('left', destLeft);
				elem.trigger('jsp-scroll-x', [-destLeft, isAtLeft, isAtRight]).trigger('scroll');
			}

			function updateVerticalArrows(isAtTop, isAtBottom)
			{
				if (settings.showArrows) {
					arrowUp[isAtTop ? 'addClass' : 'removeClass']('jspDisabled');
					arrowDown[isAtBottom ? 'addClass' : 'removeClass']('jspDisabled');
				}
			}

			function updateHorizontalArrows(isAtLeft, isAtRight)
			{
				if (settings.showArrows) {
					arrowLeft[isAtLeft ? 'addClass' : 'removeClass']('jspDisabled');
					arrowRight[isAtRight ? 'addClass' : 'removeClass']('jspDisabled');
				}
			}

			function scrollToY(destY, animate)
			{
				var percentScrolled = destY / (contentHeight - paneHeight);
				positionDragY(percentScrolled * dragMaxY, animate);
			}

			function scrollToX(destX, animate)
			{
				var percentScrolled = destX / (contentWidth - paneWidth);
				positionDragX(percentScrolled * dragMaxX, animate);
			}

			function scrollToElement(ele, stickToTop, animate)
			{
				var e, eleHeight, eleWidth, eleTop = 0, eleLeft = 0, viewportTop, viewportLeft, maxVisibleEleTop, maxVisibleEleLeft, destY, destX;

				// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
				// errors from the lookup...
				try {
					e = $(ele);
				} catch (err) {
					return;
				}
				eleHeight = e.outerHeight();
				eleWidth= e.outerWidth();

				container.scrollTop(0);
				container.scrollLeft(0);
				
				// loop through parents adding the offset top of any elements that are relatively positioned between
				// the focused element and the jspPane so we can get the true distance from the top
				// of the focused element to the top of the scrollpane...
				while (!e.is('.jspPane')) {
					eleTop += e.position().top;
					eleLeft += e.position().left;
					e = e.offsetParent();
					if (/^body|html$/i.test(e[0].nodeName)) {
						// we ended up too high in the document structure. Quit!
						return;
					}
				}

				viewportTop = contentPositionY();
				maxVisibleEleTop = viewportTop + paneHeight;
				if (eleTop < viewportTop || stickToTop) { // element is above viewport
					destY = eleTop - settings.verticalGutter;
				} else if (eleTop + eleHeight > maxVisibleEleTop) { // element is below viewport
					destY = eleTop - paneHeight + eleHeight + settings.verticalGutter;
				}
				if (destY) {
					scrollToY(destY, animate);
				}
				
				viewportLeft = contentPositionX();
	            maxVisibleEleLeft = viewportLeft + paneWidth;
	            if (eleLeft < viewportLeft || stickToTop) { // element is to the left of viewport
	                destX = eleLeft - settings.horizontalGutter;
	            } else if (eleLeft + eleWidth > maxVisibleEleLeft) { // element is to the right viewport
	                destX = eleLeft - paneWidth + eleWidth + settings.horizontalGutter;
	            }
	            if (destX) {
	                scrollToX(destX, animate);
	            }

			}

			function contentPositionX()
			{
				return -pane.position().left;
			}

			function contentPositionY()
			{
				return -pane.position().top;
			}

			function isCloseToBottom()
			{
				var scrollableHeight = contentHeight - paneHeight;
				return (scrollableHeight > 20) && (scrollableHeight - contentPositionY() < 10);
			}

			function isCloseToRight()
			{
				var scrollableWidth = contentWidth - paneWidth;
				return (scrollableWidth > 20) && (scrollableWidth - contentPositionX() < 10);
			}

			function initMousewheel()
			{
				container.unbind(mwEvent).bind(
					mwEvent,
					function (event, delta, deltaX, deltaY) {
						var dX = horizontalDragPosition, dY = verticalDragPosition;
						jsp.scrollBy(deltaX * settings.mouseWheelSpeed, -deltaY * settings.mouseWheelSpeed, false);
						// return true if there was no movement so rest of screen can scroll
						return dX == horizontalDragPosition && dY == verticalDragPosition;
					}
				);
			}

			function removeMousewheel()
			{
				container.unbind(mwEvent);
			}

			function nil()
			{
				return false;
			}

			function initFocusHandler()
			{
				pane.find(':input,a').unbind('focus.jsp').bind(
					'focus.jsp',
					function(e)
					{
						scrollToElement(e.target, false);
					}
				);
			}

			function removeFocusHandler()
			{
				pane.find(':input,a').unbind('focus.jsp');
			}
			
			function initKeyboardNav()
			{
				var keyDown, elementHasScrolled, validParents = [];
				isScrollableH && validParents.push(horizontalBar[0]);
				isScrollableV && validParents.push(verticalBar[0]);
				
				// IE also focuses elements that don't have tabindex set.
				pane.focus(
					function()
					{
						elem.focus();
					}
				);
				
				elem.attr('tabindex', 0)
					.unbind('keydown.jsp keypress.jsp')
					.bind(
						'keydown.jsp',
						function(e)
						{
							if (e.target !== this && !(validParents.length && $(e.target).closest(validParents).length)){
								return;
							}
							var dX = horizontalDragPosition, dY = verticalDragPosition;
							switch(e.keyCode) {
								case 40: // down
								case 38: // up
								case 34: // page down
								case 32: // space
								case 33: // page up
								case 39: // right
								case 37: // left
									keyDown = e.keyCode;
									keyDownHandler();
									break;
								case 35: // end
									scrollToY(contentHeight - paneHeight);
									keyDown = null;
									break;
								case 36: // home
									scrollToY(0);
									keyDown = null;
									break;
							}

							elementHasScrolled = e.keyCode == keyDown && dX != horizontalDragPosition || dY != verticalDragPosition;
							return !elementHasScrolled;
						}
					).bind(
						'keypress.jsp', // For FF/ OSX so that we can cancel the repeat key presses if the JSP scrolls...
						function(e)
						{
							if (e.keyCode == keyDown) {
								keyDownHandler();
							}
							return !elementHasScrolled;
						}
					);
				
				if (settings.hideFocus) {
					elem.css('outline', 'none');
					if ('hideFocus' in container[0]){
						elem.attr('hideFocus', true);
					}
				} else {
					elem.css('outline', '');
					if ('hideFocus' in container[0]){
						elem.attr('hideFocus', false);
					}
				}
				
				function keyDownHandler()
				{
					var dX = horizontalDragPosition, dY = verticalDragPosition;
					switch(keyDown) {
						case 40: // down
							jsp.scrollByY(settings.keyboardSpeed, false);
							break;
						case 38: // up
							jsp.scrollByY(-settings.keyboardSpeed, false);
							break;
						case 34: // page down
						case 32: // space
							jsp.scrollByY(paneHeight * settings.scrollPagePercent, false);
							break;
						case 33: // page up
							jsp.scrollByY(-paneHeight * settings.scrollPagePercent, false);
							break;
						case 39: // right
							jsp.scrollByX(settings.keyboardSpeed, false);
							break;
						case 37: // left
							jsp.scrollByX(-settings.keyboardSpeed, false);
							break;
					}

					elementHasScrolled = dX != horizontalDragPosition || dY != verticalDragPosition;
					return elementHasScrolled;
				}
			}
			
			function removeKeyboardNav()
			{
				elem.attr('tabindex', '-1')
					.removeAttr('tabindex')
					.unbind('keydown.jsp keypress.jsp');
			}

			function observeHash()
			{
				if (location.hash && location.hash.length > 1) {
					var e,
						retryInt,
						hash = escape(location.hash) // hash must be escaped to prevent XSS
						;
					try {
						e = $(hash);
					} catch (err) {
						return;
					}

					if (e.length && pane.find(hash)) {
						// nasty workaround but it appears to take a little while before the hash has done its thing
						// to the rendered page so we just wait until the container's scrollTop has been messed up.
						if (container.scrollTop() === 0) {
							retryInt = setInterval(
								function()
								{
									if (container.scrollTop() > 0) {
										scrollToElement(hash, true);
										$(document).scrollTop(container.position().top);
										clearInterval(retryInt);
									}
								},
								50
							);
						} else {
							scrollToElement(hash, true);
							$(document).scrollTop(container.position().top);
						}
					}
				}
			}

			function unhijackInternalLinks()
			{
				$('a.jspHijack').unbind('click.jsp-hijack').removeClass('jspHijack');
			}

			function hijackInternalLinks()
			{
				unhijackInternalLinks();
				$('a[href^=#]').addClass('jspHijack').bind(
					'click.jsp-hijack',
					function()
					{
						var uriParts = this.href.split('#'), hash;
						if (uriParts.length > 1) {
							hash = uriParts[1];
							if (hash.length > 0 && pane.find('#' + hash).length > 0) {
								scrollToElement('#' + hash, true);
								// Need to return false otherwise things mess up... Would be nice to maybe also scroll
								// the window to the top of the scrollpane?
								return false;
							}
						}
					}
				);
			}
			
			// Init touch on iPad, iPhone, iPod, Android
			function initTouch()
			{
				var startX,
					startY,
					touchStartX,
					touchStartY,
					moved,
					moving = false;
  
				container.unbind('touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick').bind(
					'touchstart.jsp',
					function(e)
					{
						var touch = e.originalEvent.touches[0];
						startX = contentPositionX();
						startY = contentPositionY();
						touchStartX = touch.pageX;
						touchStartY = touch.pageY;
						moved = false;
						moving = true;
					}
				).bind(
					'touchmove.jsp',
					function(ev)
					{
						if(!moving) {
							return;
						}
						
						var touchPos = ev.originalEvent.touches[0],
							dX = horizontalDragPosition, dY = verticalDragPosition;
						
						jsp.scrollTo(startX + touchStartX - touchPos.pageX, startY + touchStartY - touchPos.pageY);
						
						moved = moved || Math.abs(touchStartX - touchPos.pageX) > 5 || Math.abs(touchStartY - touchPos.pageY) > 5;
						
						// return true if there was no movement so rest of screen can scroll
						return dX == horizontalDragPosition && dY == verticalDragPosition;
					}
				).bind(
					'touchend.jsp',
					function(e)
					{
						moving = false;
						/*if(moved) {
							return false;
						}*/
					}
				).bind(
					'click.jsp-touchclick',
					function(e)
					{
						if(moved) {
							moved = false;
							return false;
						}
					}
				);
			}
			
			function destroy(){
				var currentY = contentPositionY(),
					currentX = contentPositionX();
				elem.removeClass('jspScrollable').unbind('.jsp');
				elem.replaceWith(originalElement.append(pane.children()));
				originalElement.scrollTop(currentY);
				originalElement.scrollLeft(currentX);
			}

			// Public API
			$.extend(
				jsp,
				{
					// Reinitialises the scroll pane (if it's internal dimensions have changed since the last time it
					// was initialised). The settings object which is passed in will override any settings from the
					// previous time it was initialised - if you don't pass any settings then the ones from the previous
					// initialisation will be used.
					reinitialise: function(s)
					{
						s = $.extend({}, settings, s);
						initialise(s);
					},
					// Scrolls the specified element (a jQuery object, DOM node or jQuery selector string) into view so
					// that it can be seen within the viewport. If stickToTop is true then the element will appear at
					// the top of the viewport, if it is false then the viewport will scroll as little as possible to
					// show the element. You can also specify if you want animation to occur. If you don't provide this
					// argument then the animateScroll value from the settings object is used instead.
					scrollToElement: function(ele, stickToTop, animate)
					{
						scrollToElement(ele, stickToTop, animate);
					},
					// Scrolls the pane so that the specified co-ordinates within the content are at the top left
					// of the viewport. animate is optional and if not passed then the value of animateScroll from
					// the settings object this jScrollPane was initialised with is used.
					scrollTo: function(destX, destY, animate)
					{
						scrollToX(destX, animate);
						scrollToY(destY, animate);
					},
					// Scrolls the pane so that the specified co-ordinate within the content is at the left of the
					// viewport. animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					scrollToX: function(destX, animate)
					{
						scrollToX(destX, animate);
					},
					// Scrolls the pane so that the specified co-ordinate within the content is at the top of the
					// viewport. animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					scrollToY: function(destY, animate)
					{
						scrollToY(destY, animate);
					},
					// Scrolls the pane to the specified percentage of its maximum horizontal scroll position. animate
					// is optional and if not passed then the value of animateScroll from the settings object this
					// jScrollPane was initialised with is used.
					scrollToPercentX: function(destPercentX, animate)
					{
						scrollToX(destPercentX * (contentWidth - paneWidth), animate);
					},
					// Scrolls the pane to the specified percentage of its maximum vertical scroll position. animate
					// is optional and if not passed then the value of animateScroll from the settings object this
					// jScrollPane was initialised with is used.
					scrollToPercentY: function(destPercentY, animate)
					{
						scrollToY(destPercentY * (contentHeight - paneHeight), animate);
					},
					// Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then
					// the value of animateScroll from the settings object this jScrollPane was initialised with is used.
					scrollBy: function(deltaX, deltaY, animate)
					{
						jsp.scrollByX(deltaX, animate);
						jsp.scrollByY(deltaY, animate);
					},
					// Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then
					// the value of animateScroll from the settings object this jScrollPane was initialised with is used.
					scrollByX: function(deltaX, animate)
					{
						var destX = contentPositionX() + Math[deltaX<0 ? 'floor' : 'ceil'](deltaX),
							percentScrolled = destX / (contentWidth - paneWidth);
						positionDragX(percentScrolled * dragMaxX, animate);
					},
					// Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then
					// the value of animateScroll from the settings object this jScrollPane was initialised with is used.
					scrollByY: function(deltaY, animate)
					{
						var destY = contentPositionY() + Math[deltaY<0 ? 'floor' : 'ceil'](deltaY),
							percentScrolled = destY / (contentHeight - paneHeight);
						positionDragY(percentScrolled * dragMaxY, animate);
					},
					// Positions the horizontal drag at the specified x position (and updates the viewport to reflect
					// this). animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					positionDragX: function(x, animate)
					{
						positionDragX(x, animate);
					},
					// Positions the vertical drag at the specified y position (and updates the viewport to reflect
					// this). animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					positionDragY: function(y, animate)
					{
						positionDragY(y, animate);
					},
					// This method is called when jScrollPane is trying to animate to a new position. You can override
					// it if you want to provide advanced animation functionality. It is passed the following arguments:
					//  * ele          - the element whose position is being animated
					//  * prop         - the property that is being animated
					//  * value        - the value it's being animated to
					//  * stepCallback - a function that you must execute each time you update the value of the property
					// You can use the default implementation (below) as a starting point for your own implementation.
					animate: function(ele, prop, value, stepCallback)
					{
						var params = {};
						params[prop] = value;
						ele.animate(
							params,
							{
								'duration'	: settings.animateDuration,
								'ease'		: settings.animateEase,
								'queue'		: false,
								'step'		: stepCallback
							}
						);
					},
					// Returns the current x position of the viewport with regards to the content pane.
					getContentPositionX: function()
					{
						return contentPositionX();
					},
					// Returns the current y position of the viewport with regards to the content pane.
					getContentPositionY: function()
					{
						return contentPositionY();
					},
					// Returns the width of the content within the scroll pane.
					getContentWidth: function()
					{
						return contentWidth;
					},
					// Returns the height of the content within the scroll pane.
					getContentHeight: function()
					{
						return contentHeight;
					},
					// Returns the horizontal position of the viewport within the pane content.
					getPercentScrolledX: function()
					{
						return contentPositionX() / (contentWidth - paneWidth);
					},
					// Returns the vertical position of the viewport within the pane content.
					getPercentScrolledY: function()
					{
						return contentPositionY() / (contentHeight - paneHeight);
					},
					// Returns whether or not this scrollpane has a horizontal scrollbar.
					getIsScrollableH: function()
					{
						return isScrollableH;
					},
					// Returns whether or not this scrollpane has a vertical scrollbar.
					getIsScrollableV: function()
					{
						return isScrollableV;
					},
					// Gets a reference to the content pane. It is important that you use this method if you want to
					// edit the content of your jScrollPane as if you access the element directly then you may have some
					// problems (as your original element has had additional elements for the scrollbars etc added into
					// it).
					getContentPane: function()
					{
						return pane;
					},
					// Scrolls this jScrollPane down as far as it can currently scroll. If animate isn't passed then the
					// animateScroll value from settings is used instead.
					scrollToBottom: function(animate)
					{
						positionDragY(dragMaxY, animate);
					},
					// Hijacks the links on the page which link to content inside the scrollpane. If you have changed
					// the content of your page (e.g. via AJAX) and want to make sure any new anchor links to the
					// contents of your scroll pane will work then call this function.
					hijackInternalLinks: function()
					{
						hijackInternalLinks();
					},
					// Removes the jScrollPane and returns the page to the state it was in before jScrollPane was
					// initialised.
					destroy: function()
					{
							destroy();
					}
				}
			);
			
			initialise(s);
		}

		// Pluginifying code...
		settings = $.extend({}, $.fn.jScrollPane.defaults, settings);
		
		// Apply default speed
		$.each(['mouseWheelSpeed', 'arrowButtonSpeed', 'trackClickSpeed', 'keyboardSpeed'], function() {
			settings[this] = settings[this] || settings.speed;
		});

		return this.each(
			function()
			{
				var elem = $(this), jspApi = elem.data('jsp');
				if (jspApi) {
					jspApi.reinitialise(settings);
				} else {
					jspApi = new JScrollPane(elem, settings);
					elem.data('jsp', jspApi);
				}
			}
		);
	};

	$.fn.jScrollPane.defaults = {
		showArrows					: false,
		maintainPosition			: true,
		stickToBottom				: false,
		stickToRight				: false,
		clickOnTrack				: true,
		autoReinitialise			: false,
		autoReinitialiseDelay		: 500,
		verticalDragMinHeight		: 0,
		verticalDragMaxHeight		: 99999,
		horizontalDragMinWidth		: 0,
		horizontalDragMaxWidth		: 99999,
		contentWidth				: undefined,
		animateScroll				: false,
		animateDuration				: 300,
		animateEase					: 'linear',
		hijackInternalLinks			: false,
		verticalGutter				: 4,
		horizontalGutter			: 4,
		mouseWheelSpeed				: 0,
		arrowButtonSpeed			: 0,
		arrowRepeatFreq				: 50,
		arrowScrollOnHover			: false,
		trackClickSpeed				: 0,
		trackClickRepeatFreq		: 70,
		verticalArrowPositions		: 'split',
		horizontalArrowPositions	: 'split',
		enableKeyboardNavigation	: true,
		hideFocus					: false,
		keyboardSpeed				: 0,
		initialDelay                : 300,        // Delay before starting repeating
		speed						: 30,		// Default speed when others falsey
		scrollPagePercent			: .8		// Percent of visible area scrolled when pageUp/Down or track area pressed
	};

})(jQuery,this);

;
(function($){
 $.fn.extend({
 
 	customSelectBoxStyle : function(options) {
	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  var i = 0;
	  var tmpVal;
	  return this.each(function() {
		  	var thisId = $(this).attr("id");
			var spanId = "customStyleBox_"+thisId;
			if(thisId == "edit-product-search-level-model-list" || thisId == "edit-product-search-level2-truck-clone"){
				return false;
			}
			//alert($("#"+spanId).html());
			if($("#"+spanId).html() == null){
			//return false;
			var currentSelected = $(this).find(':selected');
			$(this).after('<span id="'+spanId+'" class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next();
			var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));			
			var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
				// selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
			selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
				// Thanks to Juarez Filho & PaddyMurphy
			});
		i++;
		}
	  });
	  }
	}
	//$(this).after().find("span:gt(2)").remove();
	
 });
})(jQuery);
;
﻿/*
Name:       ImageFlow
Version:    1.3.0 (March 9 2010)
Author:     Finn Rudolph
Support:    http://finnrudolph.de/ImageFlow

License:    ImageFlow is licensed under a Creative Commons
            Attribution-Noncommercial 3.0 Unported License
            (http://creativecommons.org/licenses/by-nc/3.0/).

            You are free:
                + to Share - to copy, distribute and transmit the work
                + to Remix - to adapt the work

            Under the following conditions:
                + Attribution. You must attribute the work in the manner specified by the author or licensor
                  (but not in any way that suggests that they endorse you or your use of the work).
                + Noncommercial. You may not use this work for commercial purposes.

            + For any reuse or distribution, you must make clear to others the license terms of this work.
            + Any of the above conditions can be waived if you get permission from the copyright holder.
            + Nothing in this license impairs or restricts the author's moral rights.

Credits:    This script is based on Michael L. Perrys Cover flow in Javascript [1].
            The reflections are generated server-sided by a slightly hacked version
            of Richard Daveys easyreflections [2] written in PHP. The mouse wheel
            support is an implementation of Adomas Paltanavicius JavaScript mouse
            wheel code [3]. It also uses the domReadyEvent from Tanny O'Haley [4].

            [1] http://www.adventuresinsoftware.com/blog/?p=104#comment-1981
            [2] http://reflection.corephp.co.uk/v2.php
            [3] http://adomas.org/javascript-mouse-wheel/
            [4] http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-v
*/

/* ImageFlow constructor */
function ImageFlow ()
{
	/* Setting option defaults */
	this.defaults =
	{
		animationSpeed:     50,             /* Animation speed in ms */
		aspectRatio:        2.109,          /* Aspect ratio of the ImageFlow container (width divided by height) */
		buttons:            true,          /* Toggle navigation buttons */
		captions:           true,           /* Toggle captions */
		circular:           true,          /* Toggle circular rotation */
		imageCursor:        'pointer',      /* Cursor type for all images - default is 'default' */
		ImageFlowID:        'imageflow',    /* Default id of the ImageFlow container */
		imageFocusM:        0.5,            /* Multiplicator for the focussed image size in percent */
		imageFocusMax:      5,              /* Max number of images on each side of the focussed one */
		imagePath:          '',             /* Path to the images relative to the reflect_.php script */
		imageScaling:       true,           /* Toggle image scaling */ 
		imagesHeight:       1,           /* Height of the images div container in percent */
		imagesM:            1.1,            /* Multiplicator for all images in percent */
		onClick:            function() { document.location = '#'; },   /* Onclick behaviour */
		opacity:            false,          /* Toggle image opacity */
		opacityArray:       [10,8,6,4,2],   /* Image opacity (range: 0 to 10) first value is for the focussed image */
		percentLandscape:   290,            /* Scale landscape format */
		percentOther:       280,            /* Scale portrait and square format */
		preloadImages:      true,           /* Toggles loading bar (false: requires img attributes height and width) */
		reflections:        false,           /* Toggle reflections */
		reflectionGET:      '',             /* Pass variables via the GET method to the reflect_.php script */
		reflectionP:        0,            /* Height of the reflection in percent of the source image */
		reflectionPNG:      false,          /* Toggle reflect2.php or reflect3.php */
		reflectPath:        '',             /* Path to the reflect_.php script */
		scrollbarP:         0.9,            /* Width of the scrollbar in percent */
		slider:             true,           /* Toggle slider */
		sliderCursor:       'pointer',     /* Slider cursor type - default is 'default' */
		sliderWidth:        14,             /* Width of the slider in px */
		slideshow:          false,          /* Toggle slideshow */
		slideshowSpeed:     2000,           /* Time between slides in ms */
		slideshowAutoplay:  false,          /* Toggle automatic slideshow play on startup */
		//startID:            jQuery("#myImageFlow img").length,              /* Image ID to begin with */
		startID:            1,              /* Image ID to begin with */
		glideToStartID:     true,           /* Toggle glide animation to start ID */
		startAnimation:     true,          /* Animate images moving in from the right on startup */
		xStep:              250             /* Step width on the x-axis in px */
	};



	/* Closure for this */
	var my = this;

	
	/* Initiate ImageFlow */
	this.init = function (options)
	{
	
	var yearNavContent;
	var yearNavCount;
	yearNavCount = 5;
	yearNavContent ='';
	jQuery("#myImageFlow em.img-flow-alt-year").each(function(){
		yearNavContent +="<div id='year_nav_id_"+yearNavCount+"' class='year_navigation_cls'></div>";	
		yearNavCount++;
	});
	jQuery("#myImageFlow").after("<div class='custom_image_flow_year_nav'>"+yearNavContent+"</div>");
	
	//alert(jQuery(".year_navigation_cls:last").attr("id"));
	jQuery(".year_navigation_cls:last").attr({"style":"margin-right:0"});
	if(navigator.appVersion.indexOf("MSIE 7") != -1) {
		//jQuery(".year_navigation_cls:even").attr({"style":"width:14px"});
		//jQuery(".year_navigation_cls:first").attr({"style":"width:16px"});
		jQuery(".year_navigation_cls:even").attr({"style":"width:15px"});
		jQuery(".year_navigation_cls:first").attr({"style":"width:12px"});
		jQuery(".year_navigation_cls:last").attr({"style":"width:12px"});
		jQuery(".year_navigation_cls:eq(4)").attr({"style":"width:12px"});
		jQuery(".year_navigation_cls:eq(8)").attr({"style":"width:12px"});
	}
	jQuery(".year_navigation_cls:last").attr({"style":"width:18px"});
	/*jQuery("#imgyear").click(function(){
		alert("tesat");
		alert(jQuery(this).html());
		//my.glideTo(24);
	});*/	
	jQuery(".year_navigation_cls").click(function(){
		var getImageId = jQuery(this).attr("id");
		getImageId = getImageId.replace("year_nav_id_","");
		getImageId = parseInt(getImageId);
		my.glideTo(getImageId);
	});
		/* Evaluate options */
		for(var name in my.defaults) 
		{
			this[name] = (options !== undefined && options[name] !== undefined) ? options[name] : my.defaults[name];
		}

		/* Try to get ImageFlow div element */
		var ImageFlowDiv = document.getElementById(my.ImageFlowID);
		if(ImageFlowDiv)
		{
		
			//alert(jQuery("#myImageFlow img").length);
			var imgIndexVal = 0;
			var altContent;
			jQuery("#myImageFlow img").each(function(){
				altContent = "";
				altContent = "<div class='image-alt-year-val'>"+jQuery("#myImageFlow em.img-flow-alt-year:eq("+imgIndexVal+")").html()+"</div>";
				altContent += "<div class='image-alt-content-val'><h1>"+jQuery("#myImageFlow em.img-flow-alt-titles:eq("+imgIndexVal+")").html()+"</h1>"+jQuery("#myImageFlow em.image-flow-alt-content:eq("+imgIndexVal+")").html()+"</div><div class='clear'></div>";
				jQuery(this).attr("alt",altContent);
				imgIndexVal++;
			});
		
		
		
			/* Set it global within the ImageFlow scope */
			ImageFlowDiv.style.visibility = 'visible';
			this.ImageFlowDiv = ImageFlowDiv;

			/* Try to create XHTML structure */
			if(this.createStructure())
			{
				this.imagesDiv = document.getElementById(my.ImageFlowID+'_images');
				this.captionDiv = document.getElementById(my.ImageFlowID+'_caption');
				this.navigationDiv = document.getElementById(my.ImageFlowID+'_navigation');
				this.scrollbarDiv = document.getElementById(my.ImageFlowID+'_scrollbar');
				this.sliderDiv = document.getElementById(my.ImageFlowID+'_slider');
				this.buttonNextDiv = document.getElementById(my.ImageFlowID+'_next');
				this.buttonPreviousDiv = document.getElementById(my.ImageFlowID+'_previous');
				this.buttonSlideshow = document.getElementById(my.ImageFlowID+'_slideshow');

				this.indexArray = [];
				this.current = 0;
				this.imageID = 0;
				this.target = 0;
				this.memTarget = 0;
				this.firstRefresh = true;
				this.firstCheck = true;
				this.busy = false;

				/* Set height of the ImageFlow container and center the loading bar */
				var width = this.ImageFlowDiv.offsetWidth;
				var height = Math.round(width / my.aspectRatio);
				document.getElementById(my.ImageFlowID+'_loading_txt').style.paddingTop = ((height * 0.5) -22) + 'px';
				//ImageFlowDiv.style.height = height + 'px';

				/* Init loading progress */
				this.loadingProgress();
			}
		}
	};


	/* Create HTML Structure */
	this.createStructure = function()
	{
		/* Create images div container */
		var imagesDiv = my.Helper.createDocumentElement('div','images');

		/* Shift all images into the images div */
		var node, version, src, imageNode;
		var max = my.ImageFlowDiv.childNodes.length;
		//alert(my.ImageFlowDiv.childNodes.length);
		for(var index = 0; index < max; index++)
		{
			node = my.ImageFlowDiv.childNodes[index];
			if (node && node.nodeType == 1 && node.nodeName == 'IMG')
			{
				/* Add 'reflect.php?img=' */
				if(my.reflections === true)
				{
					version = (my.reflectionPNG) ? '3' : '2';
					src = my.imagePath+node.getAttribute('src',2);
					src = my.reflectPath+'reflect'+version+'.php?img='+src+my.reflectionGET;
					node.setAttribute('src',src);
				}

				/* Clone image nodes and append them to the images div */
				imageNode = node.cloneNode(true);
				imagesDiv.appendChild(imageNode);
			}
		}

		/* Clone some more images to make a circular animation possible */
		if(my.circular)
		{
			/* Create temporary elements to hold the cloned images */
			var first = my.Helper.createDocumentElement('div','images');
			var last = my.Helper.createDocumentElement('div','images');
			
			/* Make sure, that there are enough images to use circular mode */
			max = imagesDiv.childNodes.length;
			if(max < my.imageFocusMax)
			{
				my.imageFocusMax = max;
			}

			/* Do not clone anything if there is only one image */
			if(max > 1)
			{
				/* Clone the first and last images */
				var i;
				for(i = 0; i < max; i++)
				{
					/* Number of clones on each side equals the imageFocusMax */
					node = imagesDiv.childNodes[i];
					if(i < my.imageFocusMax)
					{
						imageNode = node.cloneNode(true);
						first.appendChild(imageNode);
					}
					if(max-i < my.imageFocusMax+1)
					{
						imageNode = node.cloneNode(true);
						last.appendChild(imageNode);
					}
				}

				/* Sort the image nodes in the following order: last | originals | first */
				for(i = 0; i < max; i++)
				{
					node = imagesDiv.childNodes[i];
					imageNode = node.cloneNode(true);
					last.appendChild(imageNode);
				}
				for(i = 0; i < my.imageFocusMax; i++)
				{
					node = first.childNodes[i];
					imageNode = node.cloneNode(true);
					last.appendChild(imageNode);
				}
				
				/* Overwrite the imagesDiv with the new order */
				imagesDiv = last;
			}
		}

		/* Create slideshow button div and append it to the images div */
		if(my.slideshow)
		{
			var slideshowButton = my.Helper.createDocumentElement('div','slideshow');
			imagesDiv.appendChild(slideshowButton);
		}

		/* Create loading text container */
		var loadingP = my.Helper.createDocumentElement('p','loading_txt');
		var loadingText = document.createTextNode(' ');
		loadingP.appendChild(loadingText);

		/* Create loading div container */
		var loadingDiv = my.Helper.createDocumentElement('div','loading');

		/* Create loading bar div container inside the loading div */
		var loadingBarDiv = my.Helper.createDocumentElement('div','loading_bar');
		loadingDiv.appendChild(loadingBarDiv);

		/* Create captions div container */
		var captionDiv = my.Helper.createDocumentElement('div','caption');

		/* Create slider and button div container inside the scrollbar div */
		var scrollbarDiv = my.Helper.createDocumentElement('div','scrollbar');
		var sliderDiv = my.Helper.createDocumentElement('div','slider');
		scrollbarDiv.appendChild(sliderDiv);
		if(my.buttons)
		{
			var buttonPreviousDiv = my.Helper.createDocumentElement('div','previous', 'button');
			var buttonNextDiv = my.Helper.createDocumentElement('div','next', 'button');
			scrollbarDiv.appendChild(buttonPreviousDiv);
			scrollbarDiv.appendChild(buttonNextDiv);
		}

		/* Create navigation div container beneath images div */
		var navigationDiv = my.Helper.createDocumentElement('div','navigation');
		navigationDiv.appendChild(captionDiv);
		navigationDiv.appendChild(scrollbarDiv);
	
		/* Update document structure and return true on success */
		var success = false;
		if (my.ImageFlowDiv.appendChild(imagesDiv) &&
			my.ImageFlowDiv.appendChild(loadingP) &&
			my.ImageFlowDiv.appendChild(loadingDiv) &&
			my.ImageFlowDiv.appendChild(navigationDiv))
		{
			/* Remove image nodes outside the images div */
			max = my.ImageFlowDiv.childNodes.length;
			for(index = 0; index < max; index++)
			{
				node = my.ImageFlowDiv.childNodes[index];
				if (node && node.nodeType == 1 && node.nodeName == 'IMG')
				{
					my.ImageFlowDiv.removeChild(node);
				}
			}
			success = true;
		}
		return success;
	};


	/* Manage loading progress and call the refresh function */
	this.loadingProgress = function()
	{
		var p = my.loadingStatus();
		if((p < 100 || my.firstCheck) && my.preloadImages)
		{
			/* Insert a short delay if the browser loads rapidly from its cache */
			if(my.firstCheck && p == 100)
			{
				my.firstCheck = false;
				window.setTimeout(my.loadingProgress, 100);
				
			}
			else
			{
				window.setTimeout(my.loadingProgress, 40);
			}
		}
		else
		{
			/* Hide loading elements */
			document.getElementById(my.ImageFlowID+'_loading_txt').style.display = 'none';
			document.getElementById(my.ImageFlowID+'_loading').style.display = 'none';

			/* Refresh ImageFlow on window resize - delay adding this event for the IE */
			window.setTimeout(my.Helper.addResizeEvent, 1000);

			/* Call refresh once on startup to display images */
			my.refresh();

			/* Only initialize navigation elements if there is more than one image */
			if(my.max > 1)
			{
				/* Initialize mouse, touch and key support */
				my.MouseWheel.init();
				my.MouseDrag.init();
				my.Touch.init();
				my.Key.init();
				
				/* Toggle slideshow */
				if(my.slideshow)
				{
					my.Slideshow.init();
				}

				/* Toggle scrollbar visibility */
				if(my.slider)
				{
					jQuery("#myImageFlow_navigation").show();
					my.scrollbarDiv.style.visibility = 'visible';
				}
			}
		}
	};


	/* Return loaded images in percent, set loading bar width and loading text */
	this.loadingStatus = function()
	{
		var max = my.imagesDiv.childNodes.length;
		var i = 0, completed = 0;
		var image = null;
		for(var index = 0; index < max; index++)
		{
			image = my.imagesDiv.childNodes[index];
			if(image && image.nodeType == 1 && image.nodeName == 'IMG')
			{
				if(image.complete)
				{
					completed++;
				}
				i++;
			}
		}

		var finished = Math.round((completed/i)*100);
		var loadingBar = document.getElementById(my.ImageFlowID+'_loading_bar');
		loadingBar.style.width = finished+'%';

		/* Do not count the cloned images */
		if(my.circular)
		{
			i = i - (my.imageFocusMax*2);
			completed = (finished < 1) ? 0 : Math.round((i/100)*finished);
		}

		var loadingP = document.getElementById(my.ImageFlowID+'_loading_txt');
		var loadingTxt = document.createTextNode('loading images '+completed+'/'+i);
		loadingP.replaceChild(loadingTxt,loadingP.firstChild);
		return finished;
	};


	/* Cache EVERYTHING that only changes on refresh or resize of the window */
	this.refresh = function()
	{
		/* Cache global variables */
		this.imagesDivWidth = my.imagesDiv.offsetWidth+my.imagesDiv.offsetLeft;
		this.maxHeight = Math.round(my.imagesDivWidth / my.aspectRatio);
		this.maxFocus = my.imageFocusMax * my.xStep;
		this.size = my.imagesDivWidth * 0.5;
		this.sliderWidth = my.sliderWidth * 0.5;
		this.scrollbarWidth = (my.imagesDivWidth - ( Math.round(my.sliderWidth) * 2)) * my.scrollbarP;
		this.imagesDivHeight = Math.round(my.maxHeight * my.imagesHeight);

		/* Change imageflow div properties */
		//my.ImageFlowDiv.style.height = my.maxHeight + 'px';

		/* Change images div properties */
		my.imagesDiv.style.height =  my.imagesDivHeight + 'px'; 
		
		/* Change images div properties */
		my.navigationDiv.style.height =  (my.maxHeight - my.imagesDivHeight) + 'px'; 

		/* Change captions div properties */
		my.captionDiv.style.width = my.imagesDivWidth + 'px';
		//my.captionDiv.style.paddingTop = Math.round(my.imagesDivWidth * 0.02) + 'px';

		/* Change scrollbar div properties */
		my.scrollbarDiv.style.width = my.scrollbarWidth + 'px';
		my.scrollbarDiv.style.marginTop = Math.round(my.imagesDivWidth * 0.02) + 'px';
		my.scrollbarDiv.style.marginLeft = Math.round(my.sliderWidth + ((my.imagesDivWidth - my.scrollbarWidth)/2)) + 'px';

		/* Set slider attributes */
		my.sliderDiv.style.cursor = my.sliderCursor;
		my.sliderDiv.onmousedown = function () { my.MouseDrag.start(this); return false;};

		if(my.buttons)
		{
			my.buttonPreviousDiv.onclick = function () { my.MouseWheel.handle(1); };
			my.buttonNextDiv.onclick = function () { my.MouseWheel.handle(-1); };
		}

		/* Set the reflection multiplicator */
		var multi = (my.reflections === true) ? my.reflectionP + 1 : 1;

		/* Set image attributes */
		var max = my.imagesDiv.childNodes.length;
		var i = 0;
		var image = null;
		for (var index = 0; index < max; index++)
		{
			image = my.imagesDiv.childNodes[index];
			if(image !== null && image.nodeType == 1 && image.nodeName == 'IMG')
			{
				this.indexArray[i] = index;

				/* Set image attributes to store values */
				image.url = image.getAttribute('longdesc');
				image.xPosition = (-i * my.xStep);
				image.i = i;

				/* Add width and height as attributes only once */
				if(my.firstRefresh)
				{
					if(image.getAttribute('width') !== null && image.getAttribute('height') !== null)
					{
						image.w = image.getAttribute('width');
						image.h = image.getAttribute('height') * multi;
					}
					else{
						image.w = image.width;
						image.h = image.height;
					}
				}

				/* Check source image format. Get image height minus reflection height! */
				if((image.w) > (image.h / (my.reflectionP + 1)))
				{
					/* Landscape format */
					image.pc = my.percentLandscape;
					image.pcMem = my.percentLandscape;
				}
				else
				{
					/* Portrait and square format */
					image.pc = my.percentOther;
					image.pcMem = my.percentOther;
				}
				
				/* Change image positioning */
				if(my.imageScaling === false)
				{
					image.style.position = 'relative';
					image.style.display = 'inline';
				}

				/* Set image cursor type */
				image.style.cursor = my.imageCursor;
				i++;
			}
		}
		this.max = my.indexArray.length;

		/* Override dynamic sizes based on the first image */
		if(my.imageScaling === false)
		{
			image = my.imagesDiv.childNodes[my.indexArray[0]];

			/* Set left padding for the first image */
			this.totalImagesWidth = image.w * my.max;
			image.style.paddingLeft = (my.imagesDivWidth/2) + (image.w/2) + 'px';

			/* Override images and navigation div height */
			my.imagesDiv.style.height =  image.h + 'px';
			my.navigationDiv.style.height =  (my.maxHeight - image.h) + 'px'; 
		}

		/* Handle startID on the first refresh */
		if(my.firstRefresh)
		{
			/* Reset variable */
			my.firstRefresh = false;

			/* Set imageID to the startID */
			my.imageID = my.startID-1;
			if (my.imageID < 0 )
			{
				my.imageID = 0;
			}

			/* Map image id range in cicular mode (ignore the cloned images) */
			if(my.circular)
			{	
				my.imageID = my.imageID + my.imageFocusMax;
			}

			/* Make sure, that the id is smaller than the image count  */
			maxId = (my.circular) ?  (my.max-(my.imageFocusMax))-1 : my.max-1;
			if (my.imageID > maxId)
			{
				my.imageID = maxId;
			}

			/* Toggle glide animation to start ID */
			if(my.glideToStartID === false)
			{
				my.moveTo(-my.imageID * my.xStep);
			}

			/* Animate images moving in from the right */
			if(my.startAnimation)
			{
				my.moveTo(5000);
			}
		}

		/* Only animate if there is more than one image */
		if(my.max > 1)
		{
			my.glideTo(my.imageID);
		}

		/* Display images in current order */
		my.moveTo(my.current);
	};


	/* Main animation function */
	this.moveTo = function(x)
	{
		this.current = x;
		this.zIndex = my.max;

		/* Main loop */
		for (var index = 0; index < my.max; index++)
		{
			var image = my.imagesDiv.childNodes[my.indexArray[index]];
			var currentImage = index * -my.xStep;

			/* Enabled image scaling */
			if(my.imageScaling)
			{
				/* Don't display images that are not conf_focussed */
				if ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget)
				{
					image.style.visibility = 'hidden';
					image.style.display = 'none';
				}
				else
				{
					image.setAttribute('id', "img_flow_"+index);
					var z = (Math.sqrt(10000 + x * x) + 100) * my.imagesM;
					var xs = x / z * my.size + my.size;

					/* Still hide images until they are processed, but set display style to block */
					image.style.display = 'block';
					
					/* Process new image height and width */
					var newImageH = (image.h / image.w * image.pc) / z * my.size;
					//var newImageH = 300;
					var newImageW = 0;
					switch (newImageH > my.maxHeight)
					{
						case false:
							newImageW = image.pc / z * my.size;
							break;

						default:
							newImageH = my.maxHeight;
							newImageW = image.w * newImageH / image.h;
							break;
					}
					
					//alert(index);
					//if(index == 1)
					//document.getElementById("img_flow_"+img_flow_i).style.height = 100;
						
					var newImageTop = (my.imagesDivHeight - newImageH) + ((newImageH / (my.reflectionP + 1)) * my.reflectionP);
					//if(index != 2)
						//var newImageH = newImageH + 30;
					/* Set new image properties */
					image.style.left = xs - (image.pc / 2) / z * my.size + 'px';
					if(newImageW && newImageH)
					{
						image.style.height = newImageH + 'px';
						image.style.width = newImageW + 'px';
						image.style.top = newImageTop + 'px';
					}
					image.style.visibility = 'visible';

					/* Set image layer through zIndex */
					switch ( x < 0 )
					{
						case true:
							this.zIndex++;
							break;

						default:
							this.zIndex = my.zIndex - 1;
							break;
					}

					/* Change zIndex and onclick function of the focussed image */
					switch ( image.i == my.imageID )
					{
						case false:
							image.onclick = function() { my.glideTo(this.i);};
							break;

						default:
							this.zIndex = my.zIndex + 1;
							if(image.url !== '')
							{
								image.onclick = my.onClick;
							}
							break;
					}
					image.style.zIndex = my.zIndex;
				}
			}

			/* Disabled image scaling */
			else
			{
				if ((currentImage + my.maxFocus) < my.memTarget || (currentImage - my.maxFocus) > my.memTarget)
				{
					image.style.visibility = 'hidden';
				}
				else
				{
					image.style.visibility = 'visible';

					/* Change onclick function of the focussed image */
					switch ( image.i == my.imageID )
					{
						case false:
							image.onclick = function() { my.glideTo(this.i);};
							break;

						default:
							if(image.url !== '')
							{
								image.onclick = my.onClick;
							}
							break;
					}
				}	
				my.imagesDiv.style.marginLeft = (x - my.totalImagesWidth) + 'px';
			}

			x += my.xStep;
		}
		
		
		
	};


	/* Initializes image gliding animation */
	this.glideTo = function(imageID)
	{
		/* Check for jumppoints */
		var jumpTarget, clonedImageID;
		if(my.circular)
		{
			/* Trigger left jumppoint */
			if(imageID+1 === my.imageFocusMax)
			{
				/* Set jump target to the same cloned image on the right */
				clonedImageID = my.max - my.imageFocusMax;
				jumpTarget = -clonedImageID * my.xStep;

				/* Set the imageID to the last image */
				imageID = clonedImageID-1 ;
			}

			/* Trigger right jumppoint */
			if(imageID === (my.max - my.imageFocusMax))
			{
				/* Set jump target to the same cloned image on the left */
				clonedImageID = my.imageFocusMax-1;
				jumpTarget = -clonedImageID * my.xStep;
				
				/* Set the imageID to the first image */
				imageID = clonedImageID+1;
			}
		}

		/* Calculate new image position target */
		var x = -imageID * my.xStep;
		this.target = x;
		this.memTarget = x;
		this.imageID = imageID;

		/* Display new caption */
		
		//alert(imageID);
		//alert(jQuery("#myImageFlow").html());
		//alert(imageID);
		//alert(jQuery(altContent).html());
		var caption = my.imagesDiv.childNodes[imageID].getAttribute('alt');
		if (caption === '' || my.captions === false)
		{
			caption = '&nbsp;';
		}
		my.captionDiv.innerHTML = caption;

		/* Set scrollbar slider to new position */
		if (my.MouseDrag.busy === false)
		{
			if(my.circular)
			{
				this.newSliderX = ((imageID-my.imageFocusMax) * my.scrollbarWidth) / (my.max-(my.imageFocusMax*2)-1) - my.MouseDrag.newX;
			}
			else
			{
				this.newSliderX = (imageID * my.scrollbarWidth) / (my.max-1) - my.MouseDrag.newX;
			}
			my.sliderDiv.style.marginLeft = (my.newSliderX - my.sliderWidth) + 'px';
			//alert((my.newSliderX - my.sliderWidth));
		}

		/* Only process if opacity or a multiplicator for the focussed image has been set */
		if(my.opacity === true || my.imageFocusM !== my.defaults.imageFocusM)
		{
			/* Set opacity for centered image */
			my.Helper.setOpacity(my.imagesDiv.childNodes[imageID], my.opacityArray[0]);
			my.imagesDiv.childNodes[imageID].pc = my.imagesDiv.childNodes[imageID].pc * my.imageFocusM;

			/* Set opacity for the other images that are displayed */
			var opacityValue = 0;
			var rightID = 0;
			var leftID = 0;
			var last = my.opacityArray.length;

			for (var i = 1; i < (my.imageFocusMax+1); i++)
			{
				if((i+1) > last)
				{
					opacityValue = my.opacityArray[last-1];
				}
				else
				{
					opacityValue = my.opacityArray[i];
				}

				rightID = imageID + i;
				leftID = imageID - i;

				if (rightID < my.max)
				{
					my.Helper.setOpacity(my.imagesDiv.childNodes[rightID], opacityValue);
					my.imagesDiv.childNodes[rightID].pc = my.imagesDiv.childNodes[rightID].pcMem;
				}
				if (leftID >= 0)
				{
					my.Helper.setOpacity(my.imagesDiv.childNodes[leftID], opacityValue);
					my.imagesDiv.childNodes[leftID].pc = my.imagesDiv.childNodes[leftID].pcMem;
				}
			}
		}

		/* Move the images to the jump target */
		if(jumpTarget)
		{
			my.moveTo(jumpTarget);
		}

		/* Animate gliding to new x position */
		if (my.busy === false)
		{
			my.busy = true;
			my.animate();
		}
	};


	/* Animates image gliding */
	this.animate = function()
	{
		switch (my.target < my.current-1 || my.target > my.current+1)
		{
			case true:
				my.moveTo(my.current + (my.target-my.current)/3);
				window.setTimeout(my.animate, my.animationSpeed);
				my.busy = true;
				break;

			default:
				my.busy = false;
				break;
		}
	};


	/* Used by user events to call the glideTo function */
	this.glideOnEvent = function(imageID)
	{
		/* Interrupt slideshow on mouse wheel, keypress, touch and mouse drag */
		if(my.slideshow)
		{
			my.Slideshow.interrupt();
		}
		
		/* Glide to new imageID */
		my.glideTo(imageID);
	};


	/* Slideshow function */
	this.Slideshow =
	{
		direction: 1,
		
		init: function()
		{
			/* Call start() if autoplay is enabled, stop() if it is disabled */
			(my.slideshowAutoplay) ? my.Slideshow.start() : my.Slideshow.stop();	
		},

		interrupt: function()
		{	
			/* Remove interrupt event */
			my.Helper.removeEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt);
			
			/* Interrupt the slideshow */
			my.Slideshow.stop();
		},

		addInterruptEvent: function()
		{
			/* A click anywhere inside the ImageFlow div interrupts the slideshow */
			my.Helper.addEvent(my.ImageFlowDiv,'click',my.Slideshow.interrupt);
		},

		start: function()
		{
			/* Set button style to pause */
			my.Helper.setClassName(my.buttonSlideshow, 'slideshow pause');

			/* Set onclick behaviour to stop */
			my.buttonSlideshow.onclick = function () { my.Slideshow.stop(); };

			/* Set slide interval */
			my.Slideshow.action = window.setInterval(my.Slideshow.slide, my.slideshowSpeed);

			/* Allow the user to always interrupt the slideshow */
			window.setTimeout(my.Slideshow.addInterruptEvent, 100);
		},

		stop: function()
		{
			/* Set button style to play */
			my.Helper.setClassName(my.buttonSlideshow, 'slideshow play');
			
			/* Set onclick behaviour to start */
			my.buttonSlideshow.onclick = function () { my.Slideshow.start(); };
			
			/* Clear slide interval */
			window.clearInterval(my.Slideshow.action);
		},

		slide: function()
		{
			var newImageID = my.imageID + my.Slideshow.direction;
			var reverseDirection = false;
			
			/* Reverse direction at the last image on the right */
			if(newImageID === my.max)
			{
				my.Slideshow.direction = -1;
				reverseDirection = true;
			}
			
			/* Reverse direction at the last image on the left */
			if(newImageID < 0)
			{
				my.Slideshow.direction = 1;
				reverseDirection = true;
			}
			
			/* If direction is reversed recall this method, else call the glideTo method */
			(reverseDirection) ? my.Slideshow.slide() : my.glideTo(newImageID);
		}
	};


	/* Mouse Wheel support */
	this.MouseWheel =
	{
		init: function()
		{
			/* Init mouse wheel listener */
			if(window.addEventListener)
			{
				my.ImageFlowDiv.addEventListener('DOMMouseScroll', my.MouseWheel.get, false);
			}
			my.Helper.addEvent(my.ImageFlowDiv,'mousewheel',my.MouseWheel.get);
		},

		get: function(event)
		{
			var delta = 0;
			if (!event)
			{
				event = window.event;
			}
			if (event.wheelDelta)
			{
				delta = event.wheelDelta / 120;
			}
			else if (event.detail)
			{
				delta = -event.detail / 3;
			}
			if (delta)
			{
				my.MouseWheel.handle(delta);
			}
			my.Helper.suppressBrowserDefault(event);
		},

		handle: function(delta)
		{
			var change = false;
			var newImageID = 0;
			if(delta > 0)
			{
				if(my.imageID >= 1)
				{
					newImageID = my.imageID -1;
					change = true;
				}
			}
			else
			{
				if(my.imageID < (my.max-1))
				{
					newImageID = my.imageID +1;
					change = true;
				}
			}

			/* Glide to next (mouse wheel down) / previous (mouse wheel up) image  */
			if(change)
			{
				my.glideOnEvent(newImageID);
			}
		}
	};


	/* Mouse Dragging */
	this.MouseDrag =
	{
		object: null,
		objectX: 0,
		mouseX: 0,
		newX: 0,
		busy: false,

		/* Init mouse event listener */
		init: function()
		{
			my.Helper.addEvent(my.ImageFlowDiv,'mousemove',my.MouseDrag.drag);
			my.Helper.addEvent(my.ImageFlowDiv,'mouseup',my.MouseDrag.stop);
			my.Helper.addEvent(document,'mouseup',my.MouseDrag.stop);

			/* Avoid text and image selection while dragging  */
			my.ImageFlowDiv.onselectstart = function ()
			{
				var selection = true;
				if (my.MouseDrag.busy)
				{
					selection = false;
				}
				return selection;
			};
		},

		start: function(o)
		{
			my.MouseDrag.object = o;
			my.MouseDrag.objectX = my.MouseDrag.mouseX - o.offsetLeft + my.newSliderX;
		},

		stop: function()
		{
			my.MouseDrag.object = null;
			my.MouseDrag.busy = false;
		},

		drag: function(e)
		{
			var posx = 0;
			if (!e)
			{
				e = window.event;
			}
			if (e.pageX)
			{
				posx = e.pageX;
			}
			else if (e.clientX)
			{
				posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
			}
			my.MouseDrag.mouseX = posx;

			if(my.MouseDrag.object !== null)
			{
				var newX = (my.MouseDrag.mouseX - my.MouseDrag.objectX) + my.sliderWidth;

				/* Make sure, that the slider is moved in proper relation to previous movements by the glideTo function */
				if(newX < ( - my.newSliderX))
				{
					newX = - my.newSliderX;
				}
				if(newX > (my.scrollbarWidth - my.newSliderX))
				{
					newX = my.scrollbarWidth - my.newSliderX;
				}

				/* Set new slider position */
				var step, imageID;
				if(my.circular)
				{
					step = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-(my.imageFocusMax*2)-1));
					imageID = Math.round(step)+my.imageFocusMax;
				}
				else
				{
					step = (newX + my.newSliderX) / (my.scrollbarWidth / (my.max-1));
					imageID = Math.round(step);
				}
				my.MouseDrag.newX = newX;
				my.MouseDrag.object.style.left = newX + 'px';
				if(my.imageID !== imageID)
				{
					my.glideOnEvent(imageID);
				}
				my.MouseDrag.busy = true;
			}
		}
	};


	/* Safari touch events on the iPhone and iPod Touch */
	this.Touch =
	{
		x: 0,
		startX: 0,
		stopX: 0,
		busy: false,
		first: true,

		/* Init touch event listener */
		init: function()
		{
			my.Helper.addEvent(my.navigationDiv,'touchstart',my.Touch.start);
			my.Helper.addEvent(document,'touchmove',my.Touch.handle);
			my.Helper.addEvent(document,'touchend',my.Touch.stop);	
		},
		
		isOnNavigationDiv: function(e)
		{
			var state = false;
			if(e.touches)
			{
				var target = e.touches[0].target;
				if(target === my.navigationDiv || target === my.sliderDiv || target === my.scrollbarDiv)
				{
					state = true;
				}
			}
			return state;
		},

		getX: function(e)
		{
			var x = 0;
			if(e.touches)
			{
				x = e.touches[0].pageX;
			}
			return x;
		},

		start: function(e)
		{
			my.Touch.startX = my.Touch.getX(e);
			my.Touch.busy = true;
			my.Helper.suppressBrowserDefault(e);
		},

		isBusy: function()
		{
			var busy = false;
			if(my.Touch.busy)
			{
				busy = true;
			}
			return busy;
		},

		/* Handle touch event position within the navigation div */
		handle: function(e)
		{
			if(my.Touch.isBusy && my.Touch.isOnNavigationDiv(e))
			{
				var max = (my.circular) ? (my.max-(my.imageFocusMax*2)-1) : (my.max-1);
				if(my.Touch.first)
				{
					my.Touch.stopX = (max - my.imageID) * (my.imagesDivWidth / max);
					my.Touch.first = false;
				}
				var newX = -(my.Touch.getX(e) - my.Touch.startX - my.Touch.stopX);

				/* Map x-axis touch coordinates in range of the ImageFlow width */
				if(newX < 0)
				{
					newX = 0;
				}
				if(newX > my.imagesDivWidth)
				{
					newX = my.imagesDivWidth;
				}

				my.Touch.x = newX;
				
				var imageID = Math.round(newX / (my.imagesDivWidth / max));
				imageID = max - imageID;
				if(my.imageID !== imageID)
				{
					if(my.circular)
					{
						imageID = imageID + my.imageFocusMax;
					}
					my.glideOnEvent(imageID);
				}
				my.Helper.suppressBrowserDefault(e);
			}
		},

		stop: function()
		{
			my.Touch.stopX = my.Touch.x;
			my.Touch.busy = false;
		}
	};


	/* Key support */
	this.Key =
	{
		/* Init key event listener */
		init: function()
		{
			document.onkeydown = function(event){ my.Key.handle(event); };
		},

		/* Handle the arrow keys */
		handle: function(event)
		{
			var charCode  = my.Key.get(event);
			switch (charCode)
			{
				/* Right arrow key */
				case 39:
					my.MouseWheel.handle(-1);
					break;

				/* Left arrow key */
				case 37:
					my.MouseWheel.handle(1);
					break;
			}
		},

		/* Get the current keycode */
		get: function(event)
		{
			event = event || window.event;
			return event.keyCode;
		}
	};


	/* Helper functions */
	this.Helper =
	{
		/* Add events */
		addEvent: function(obj, type, fn)
		{
			if(obj.addEventListener)
			{
				obj.addEventListener(type, fn, false);
			}
			else if(obj.attachEvent)
			{
				obj["e"+type+fn] = fn;
				obj[type+fn] = function() { obj["e"+type+fn]( window.event ); };
				obj.attachEvent( "on"+type, obj[type+fn] );
			}
		},

		/* Remove events */
		removeEvent: function( obj, type, fn )
		{
			if (obj.removeEventListener)
			{
				obj.removeEventListener( type, fn, false );
			}
			else if (obj.detachEvent)
			{
				/* The IE breaks if you're trying to detach an unattached event http://msdn.microsoft.com/en-us/library/ms536411(VS.85).aspx */
				if(obj[type+fn] === undefined)
				{
					alert('Helper.removeEvent » Pointer to detach event is undefined - perhaps you are trying to detach an unattached event?');
				}
				obj.detachEvent( 'on'+type, obj[type+fn] );
				obj[type+fn] = null;
				obj['e'+type+fn] = null;
			}
		},

		/* Set image opacity */
		setOpacity: function(object, value)
		{
			if(my.opacity === true)
			{
				object.style.opacity = value/10;
				object.style.filter = 'alpha(opacity=' + value*10 + ')';
			}
		},

		/* Create HTML elements */
		createDocumentElement: function(type, id, optionalClass)
		{
			var element = document.createElement(type);
			element.setAttribute('id', my.ImageFlowID+'_'+id);
			if(optionalClass !== undefined)
			{
				id += ' '+optionalClass;
			}
			my.Helper.setClassName(element, id);
			return element;
		},

		/* Set CSS class */
		setClassName: function(element, className)
		{
			if(element)
			{
				element.setAttribute('class', className);
				element.setAttribute('className', className);
			}
		},

		/* Suppress default browser behaviour to avoid image/text selection while dragging */
		suppressBrowserDefault: function(e)
		{
			if(e.preventDefault)
			{
				e.preventDefault();
			}
			else
			{
				e.returnValue = false;
			}
			return false;
		},

		/* Add functions to the window.onresize event - can not be done by addEvent */
		addResizeEvent: function()
		{
			var otherFunctions = window.onresize;
			if(typeof window.onresize != 'function')
			{
				window.onresize = function()
				{
					my.refresh();
				};
			}
			else
			{
				window.onresize = function(){
					if (otherFunctions)
					{
						otherFunctions();
					}
					my.refresh();
				};
			}
		}
	};
}

/* DOMContentLoaded event handler - by Tanny O'Haley [4] */
var domReadyEvent =
{
	name: "domReadyEvent",
	/* Array of DOMContentLoaded event handlers.*/
	events: {},
	domReadyID: 1,
	bDone: false,
	DOMContentLoadedCustom: null,

	/* Function that adds DOMContentLoaded listeners to the array.*/
	add: function(handler)
	{
		/* Assign each event handler a unique ID. If the handler has an ID, it has already been added to the events object or been run.*/
		if (!handler.$$domReadyID)
		{
			handler.$$domReadyID = this.domReadyID++;

			/* If the DOMContentLoaded event has happened, run the function. */
			if(this.bDone)
			{
				handler();
			}

			/* store the event handler in the hash table */
			this.events[handler.$$domReadyID] = handler;
		}
	},

	remove: function(handler)
	{
		/* Delete the event handler from the hash table */
		if (handler.$$domReadyID)
		{
			delete this.events[handler.$$domReadyID];
		}
	},

	/* Function to process the DOMContentLoaded events array. */
	run: function()
	{
		/* quit if this function has already been called */
		if (this.bDone)
		{
			return;
		}

		/* Flag this function so we don't do the same thing twice */
		this.bDone = true;

		/* iterates through array of registered functions */
		for (var i in this.events)
		{
			this.events[i]();
		}
	},

	schedule: function()
	{
		/* Quit if the init function has already been called*/
		if (this.bDone)
		{
			return;
		}

		/* First, check for Safari or KHTML.*/
		if(/KHTML|WebKit/i.test(navigator.userAgent))
		{
			if(/loaded|complete/.test(document.readyState))
			{
				this.run();
			}
			else
			{
				/* Not ready yet, wait a little more.*/
				setTimeout(this.name + ".schedule()", 100);
			}
		}
		else if(document.getElementById("__ie_onload"))
		{
			/* Second, check for IE.*/
			return true;
		}

		/* Check for custom developer provided function.*/
		if(typeof this.DOMContentLoadedCustom === "function")
		{
			/* if DOM methods are supported, and the body element exists (using a double-check
			including document.body, for the benefit of older moz builds [eg ns7.1] in which
			getElementsByTagName('body')[0] is undefined, unless this script is in the body section) */
			if(typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null))
			{
				/* Call custom function. */
				if(this.DOMContentLoadedCustom())
				{
					this.run();
				}
				else
				{
					/* Not ready yet, wait a little more. */
					setTimeout(this.name + ".schedule()", 250);
				}
			}
		}
		return true;
	},

	init: function()
	{
		/* If addEventListener supports the DOMContentLoaded event.*/
		if(document.addEventListener)
		{
			document.addEventListener("DOMContentLoaded", function() { domReadyEvent.run(); }, false);
		}

		/* Schedule to run the init function.*/
		setTimeout("domReadyEvent.schedule()", 100);

		function run()
		{
			domReadyEvent.run();
		}

		/* Just in case window.onload happens first, add it to onload using an available method.*/
		if(typeof addEvent !== "undefined")
		{
			addEvent(window, "load", run);
		}
		else if(document.addEventListener)
		{
			document.addEventListener("load", run, false);
		}
		else if(typeof window.onload === "function")
		{
			var oldonload = window.onload;
			window.onload = function()
			{
				domReadyEvent.run();
				oldonload();
			};
		}
		else
		{
			window.onload = run;
		}

		/* for Internet Explorer */
		/*@cc_on
			@if (@_win32 || @_win64)
			document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
			var script = document.getElementById("__ie_onload");
			script.onreadystatechange = function()
			{
				if (this.readyState == "complete")
				{
					domReadyEvent.run(); // call the onload handler
				}
			};
			@end
		@*/
	}
};

var domReady = function(handler) { domReadyEvent.add(handler); };
domReadyEvent.init();


/* Create ImageFlow instances when the DOM structure has been loaded */
domReady(function()
{
	var instanceOne = new ImageFlow();
	instanceOne.init({ ImageFlowID:'myImageFlow' });
});

;
/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

/*global window, jQuery */
(function($) {
    // Default configuration properties.
    var defaults = {
        vertical: false,
        rtl: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        setupCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        animationStepCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null,
        itemFallbackDimension: null
    }, windowLoaded = false;

    $(window).bind('load.jcarousel', function() { windowLoaded = true; });

    /**
     * The jCarousel object.
     *
     * @constructor
     * @class jcarousel
     * @param e {HTMLElement} The element to create the carousel for.
     * @param o {Object} A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked          = false;
        this.autoStopped     = false;

        this.container       = null;
        this.clip            = null;
        this.list            = null;
        this.buttonNext      = null;
        this.buttonPrev      = null;
        this.buttonNextState = null;
        this.buttonPrevState = null;

        // Only set if not explicitly passed as option
        if (!o || o.rtl === undefined) {
            this.options.rtl = ($(e).attr('dir') || $('html').attr('dir') || '').toLowerCase() == 'rtl';
        }

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? (this.options.rtl ? 'right' : 'left') : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                skin = split[i];
                break;
            }
        }

        if (e.nodeName.toUpperCase() == 'UL' || e.nodeName.toUpperCase() == 'OL') {
            this.list      = $(e);
            this.clip      = this.list.parents('.jcarousel-clip');
            this.container = this.list.parents('.jcarousel-container');
        } else {
            this.container = $(e);
            this.list      = this.container.find('ul,ol').eq(0);
            this.clip      = this.container.find('.jcarousel-clip');
        }

        if (this.clip.size() === 0) {
            this.clip = this.list.wrap('<div></div>').parent();
        }

        if (this.container.size() === 0) {
            this.container = this.clip.wrap('<div></div>').parent();
        }

        if (skin !== '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1) {
            this.container.wrap('<div class=" '+ skin + '"></div>');
        }

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() === 0 && this.options.buttonPrevHTML !== null) {
            this.buttonPrev = $(this.options.buttonPrevHTML).appendTo(this.container);
        }

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() === 0 && this.options.buttonNextHTML !== null) {
            this.buttonNext = $(this.options.buttonNextHTML).appendTo(this.container);
        }

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip')).css({
            position: 'relative'
        });

        this.list.addClass(this.className('jcarousel-list')).css({
            overflow: 'hidden',
            position: 'relative',
            top: 0,
            margin: 0,
            padding: 0
        }).css((this.options.rtl ? 'right' : 'left'), 0);

        this.container.addClass(this.className('jcarousel-container')).css({
            position: 'relative'
        });

        if (!this.options.vertical && this.options.rtl) {
            this.container.addClass('jcarousel-direction-rtl').attr('dir', 'rtl');
        }

        var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, j = this.options.offset;
            li.each(function() {
                self.format(this, j++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, (wh + 100) + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined) {
                this.options.size = li.size();
            }
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { 
            if (self.resizeTimer) {
                clearTimeout(self.resizeTimer);
            }

            self.resizeTimer = setTimeout(function() {
                self.reload();
            }, 100);
        };

        if (this.options.initCallback !== null) {
            this.options.initCallback(this, 'init');
        }

        if (!windowLoaded && $.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load.jcarousel', function() { self.setup(); });
        } else {
            this.setup();
        }
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.8'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @method setup
         * @return undefined
         */
        setup: function() {
            this.first       = null;
            this.last        = null;
            this.prevFirst   = null;
            this.prevLast    = null;
            this.animating   = false;
            this.timer       = null;
            this.resizeTimer = null;
            this.tail        = null;
            this.inTail      = false;

            if (this.locked) {
                return;
            }

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start, true);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize.jcarousel', this.funcResize).bind('resize.jcarousel', this.funcResize);

            if (this.options.setupCallback !== null) {
                this.options.setupCallback(this);
            }
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @method reset
         * @return undefined
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback !== null) {
                this.options.initCallback(this, 'reset');
            }

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @method reload
         * @return undefined
         */
        reload: function() {
            if (this.tail !== null && this.inTail) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);
            }

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback !== null) {
                this.options.reloadCallback(this);
            }

            if (this.options.visible !== null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                this.list.children('li').each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first) {
                        lt = wh;
                    }
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @method lock
         * @return undefined
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @method unlock
         * @return undefined
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @method size
         * @return undefined
         * @param s {Number} The size of the carousel.
         */
        size: function(s) {
            if (s !== undefined) {
                this.options.size = s;
                if (!this.locked) {
                    this.buttons();
                }
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @method get
         * @return bool
         * @param i {Number} The index of the (first) element.
         * @param i2 {Number} The index of the last element.
         */
        has: function(i, i2) {
            if (i2 === undefined || !i2) {
                i2 = i;
            }

            if (this.options.size !== null && i2 > this.options.size) {
                i2 = this.options.size;
            }

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder')) {
                    return false;
                }
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @method get
         * @return jQuery
         * @param i {Number} The index of the element.
         */
        get: function(i) {
            return $('>.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @method add
         * @return jQuery
         * @param i {Number} The index of the element.
         * @param s {String} The innerHTML of the element.
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, n = $(s);

            if (e.length === 0) {
                var c, j = $jc.intval(i);
                e = this.create(i);
                while (true) {
                    c = this.get(--j);
                    if (j <= 0 || c.length) {
                        if (j <= 0) {
                            this.list.prepend(e);
                        } else {
                            c.after(e);
                        }
                        break;
                    }
                }
            } else {
                old = this.dimension(e);
            }

            if (n.get(0).nodeName.toUpperCase() == 'LI') {
                e.replaceWith(n);
                e = n;
            } else {
                e.empty().append(s);
            }

            this.format(e.removeClass(this.className('jcarousel-item-placeholder')), i);

            var di = this.options.visible !== null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');
            }

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @method remove
         * @return undefined
         * @param i {Number} The index of the element.
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last)) {
                return;
            }

            var d = this.dimension(e);

            if (i < this.first) {
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');
            }

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @method next
         * @return undefined
         */
        next: function() {
            if (this.tail !== null && !this.inTail) {
                this.scrollTail(false);
            } else {
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size !== null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
            }
        },

        /**
         * Moves the carousel backwards.
         *
         * @method prev
         * @return undefined
         */
        prev: function() {
            if (this.tail !== null && this.inTail) {
                this.scrollTail(true);
            } else {
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size !== null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
            }
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @method scrollTail
         * @return undefined
         * @param b {Boolean} Whether scroll the tail back or forward.
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail) {
                return;
            }

            this.pauseAuto();

            var pos  = $jc.intval(this.list.css(this.lt));

            pos = !b ? pos - this.tail : pos + this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @method scroll
         * @return undefined
         * @param i {Number} The index of the element to scoll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        scroll: function(i, a) {
            if (this.locked || this.animating) {
                return;
            }

            this.pauseAuto();
            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @method pos
         * @return {Number}
         * @param i {Number} The index of the element to scoll to.
         * @param fv {Boolean} Whether to force last item to be visible.
         */
        pos: function(i, fv) {
            var pos  = $jc.intval(this.list.css(this.lt));

            if (this.locked || this.animating) {
                return pos;
            }

            if (this.options.wrap != 'circular') {
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);
            }

            var back = this.first > i;

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0, g;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length === 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);

                    if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length) {
                            e = this.add(j, g.clone(true));
                        }
                    }
                }

                c = e;
                d = this.dimension(e);

                if (p) {
                    l += d;
                }

                if (this.first !== null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size === null || j <= this.options.size)))) {
                    pos = back ? pos + d : pos - d;
                }
            }

            // Calculate visible items
            var clipping = this.clipping(), cache = [], visible = 0, v = 0;
            c = this.get(i - 1);
            j = i;

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length === 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    if (c.length === 0) {
                        this.list.prepend(e);
                    } else {
                        c[back ? 'before' : 'after' ](e);
                    }

                    if (this.first !== null && this.options.wrap == 'circular' && this.options.size !== null && (j <= 0 || j > this.options.size)) {
                        g = this.get(this.index(j));
                        if (g.length) {
                            e = this.add(j, g.clone(true));
                        }
                    }
                }

                c = e;
                d = this.dimension(e);
                if (d === 0) {
                    throw new Error('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size) {
                    cache.push(e);
                } else if (p) {
                    l += d;
                }

                v += d;

                if (v >= clipping) {
                    break;
                }

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++) {
                cache[x].remove();
            }

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size) {
                last = this.options.size;
            }

            if (j > last) {
                visible = 0;
                j = last;
                v = 0;
                while (++visible) {
                    e = this.get(j--);
                    if (!e.length) {
                        break;
                    }
                    v += this.dimension(e);
                    if (v >= clipping) {
                        break;
                    }
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1) {
                first = 1;
            }

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.intval(this.get(last).css(!this.options.vertical ? 'marginRight' : 'marginBottom'));
                if ((v - m) > clipping) {
                    this.tail = v - clipping - m;
                }
            }

            if (fv && i === this.options.size && this.tail) {
                pos -= this.tail;
                this.inTail = true;
            }

            // Adjust position
            while (i-- > first) {
                pos += this.dimension(this.get(i));
            }

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @method animate
         * @return undefined
         * @param p {Number} Position to scroll to.
         * @param a {Boolean} Flag indicating whether to perform animation.
         */
        animate: function(p, a) {
            if (this.locked || this.animating) {
                return;
            }

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p === 0) {
                    self.list.css(self.lt,  0);
                }

                if (!self.autoStopped && (self.options.wrap == 'circular' || self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size === null || self.last < self.options.size || (self.last == self.options.size && self.tail !== null && !self.inTail))) {
                    self.startAuto();
                }

                self.buttons();
                self.notify('onAfterAnimation');

                // This function removes items which are appended automatically for circulation.
                // This prevents the list from growing infinitely.
                if (self.options.wrap == 'circular' && self.options.size !== null) {
                    for (var i = self.prevFirst; i <= self.prevLast; i++) {
                        if (i !== null && !(i >= self.first && i <= self.last) && (i < 1 || i > self.options.size)) {
                            self.remove(i);
                        }
                    }
                }
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a === false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? (this.options.rtl ? {'right': p} : {'left': p}) : {'top': p};
                // Define animation settings.
                var settings = {
                    duration: this.options.animation,
                    easing:   this.options.easing,
                    complete: scrolled
                };
                // If we have a step callback, specify it as well.
                if ($.isFunction(this.options.animationStepCallback)) {
                    settings.step = this.options.animationStepCallback;
                }
                // Start the animation.
                this.list.animate(o, settings);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @method auto
         * @return undefined
         * @param s {Number} Seconds to periodically autoscroll the content.
         */
        startAuto: function(s) {
            if (s !== undefined) {
                this.options.auto = s;
            }

            if (this.options.auto === 0) {
                return this.stopAuto();
            }

            if (this.timer !== null) {
                return;
            }

            this.autoStopped = false;

            var self = this;
            this.timer = window.setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @method stopAuto
         * @return undefined
         */
        stopAuto: function() {
            this.pauseAuto();
            this.autoStopped = true;
        },

        /**
         * Pauses autoscrolling.
         *
         * @method pauseAuto
         * @return undefined
         */
        pauseAuto: function() {
            if (this.timer === null) {
                return;
            }

            window.clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @method buttons
         * @return undefined
         */
        buttons: function(n, p) {
            if (n == null) {
                n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size === null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size !== null && this.last >= this.options.size) {
                    n = this.tail !== null && !this.inTail;
                }
            }

            if (p == null) {
                p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size !== null && this.first == 1) {
                    p = this.tail !== null && this.inTail;
                }
            }

            var self = this;

            if (this.buttonNext.size() > 0) {
                this.buttonNext.unbind(this.options.buttonNextEvent + '.jcarousel', this.funcNext);

                if (n) {
                    this.buttonNext.bind(this.options.buttonNextEvent + '.jcarousel', this.funcNext);
                }

                this.buttonNext[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);

                if (this.options.buttonNextCallback !== null && this.buttonNext.data('jcarouselstate') != n) {
                    this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); }).data('jcarouselstate', n);
                }
            } else {
                if (this.options.buttonNextCallback !== null && this.buttonNextState != n) {
                    this.options.buttonNextCallback(self, null, n);
                }
            }

            if (this.buttonPrev.size() > 0) {
                this.buttonPrev.unbind(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);

                if (p) {
                    this.buttonPrev.bind(this.options.buttonPrevEvent + '.jcarousel', this.funcPrev);
                }

                this.buttonPrev[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

                if (this.options.buttonPrevCallback !== null && this.buttonPrev.data('jcarouselstate') != p) {
                    this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); }).data('jcarouselstate', p);
                }
            } else {
                if (this.options.buttonPrevCallback !== null && this.buttonPrevState != p) {
                    this.options.buttonPrevCallback(self, null, p);
                }
            }

            this.buttonNextState = n;
            this.buttonPrevState = p;
        },

        /**
         * Notify callback of a specified event.
         *
         * @method notify
         * @return undefined
         * @param evt {String} The event name
         */
        notify: function(evt) {
            var state = this.prevFirst === null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == null || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation')) {
                return;
            }

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback)) {
                return;
            }

            var self = this;

            if (i1 === undefined) {
                callback(self, state, evt);
            } else if (i2 === undefined) {
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            } else {
                var call = function(i) {
                    self.get(i).each(function() { callback(self, this, i, state, evt); });
                };
                for (var i = i1; i <= i2; i++) {
                    if (i !== null && !(i >= i3 && i <= i4)) {
                        call(i);
                    }
                }
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            e = $(e);
            var split = e.get(0).className.split(' ');
            for (var j = 0; j < split.length; j++) {
                if (split[j].indexOf('jcarousel-') != -1) {
                    e.removeClass(split[j]);
                }
            }
            e.addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i)).css({
                'float': (this.options.rtl ? 'right' : 'left'),
                'list-style': 'none'
            }).attr('jcarouselindex', i);
            return e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = $(e);

            if (d == null) {
                return !this.options.vertical ?
                       (el.outerWidth(true) || $jc.intval(this.options.itemFallbackDimension)) :
                       (el.outerHeight(true) || $jc.intval(this.options.itemFallbackDimension));
            } else {
                var w = !this.options.vertical ?
                    d - $jc.intval(el.css('marginLeft')) - $jc.intval(el.css('marginRight')) :
                    d - $jc.intval(el.css('marginTop')) - $jc.intval(el.css('marginBottom'));

                $(el).css(this.wh, w + 'px');

                return this.dimension(el);
            }
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == null) {
                s = this.options.size;
            }

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @method defaults
         * @return {Object}
         * @param d {Object} A set of key/value pairs to set as configuration properties.
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        intval: function(v) {
            v = parseInt(v, 10);
            return isNaN(v) ? 0 : v;
        },

        windowLoaded: function() {
            windowLoaded = true;
        }
    });

    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *   </div>
     * </div>
     *
     * @method jcarousel
     * @return jQuery
     * @param o {Hash|String} A set of key/value pairs to set as configuration properties or a method name to call on a formerly created instance.
     */
    $.fn.jcarousel = function(o) {
        if (typeof o == 'string') {
            var instance = $(this).data('jcarousel'), args = Array.prototype.slice.call(arguments, 1);
            return instance[o].apply(instance, args);
        } else {
            return this.each(function() {
                var instance = $(this).data('jcarousel');
                if (instance) {
                    if (o) {
                        $.extend(instance.options, o);
                    }
                    instance.reload();
                } else {
                    $(this).data('jcarousel', new $jc(this, o));
                }
            });
        }
    };

})(jQuery);
;
/*
 * Supersubs v0.2b - jQuery plugin - LAST UPDATE: MARCH 23rd, 2011
 * Copyright (c) 2008 Joel Birch
 *
 * Jan 16th, 2011 - Modified a little in order to work with NavBar menus as well.
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of
 * their longest list item children. If you use this, please expect bugs and report them
 * to the jQuery Google Group with the word 'Superfish' in the subject line.
 *
 */

(function($){ // $ will refer to jQuery within this closure

  $.fn.supersubs = function(options){
    var opts = $.extend({}, $.fn.supersubs.defaults, options);
	// return original object to support chaining
    return this.each(function() {
      // cache selections
      var $$ = $(this);
      // support metadata
      var o = $.meta ? $.extend({}, opts, $$.data()) : opts;
      // get the font size of menu.
      // .css('fontSize') returns various results cross-browser, so measure an em dash instead
      var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({
        'padding' : 0,
        'position' : 'absolute',
        'top' : '-99999em',
        'width' : 'auto'
      }).appendTo($$).width(); //clientWidth is faster, but was incorrect here
      // remove em dash
      $('#menu-fontsize').remove();

      // Jump on level if it's a "NavBar"
      if ($$.hasClass('sf-navbar')) {
        $$ = $('li > ul', $$);
      }
      // cache all ul elements 
      $ULs = $$.find('ul:not(.sf-megamenu)');
      // loop through each ul in menu
      $ULs.each(function(i) {
        // cache this ul
        var $ul = $ULs.eq(i);
        // get all (li) children of this ul
        var $LIs = $ul.children();
        // get all anchor grand-children
        var $As = $LIs.children('a');
        // force content to one line and save current float property
        var liFloat = $LIs.css('white-space','nowrap').css('float');
        // remove width restrictions and floats so elements remain vertically stacked
        var emWidth = $ul.add($LIs).add($As).css({
          'float' : 'none',
          'width'  : 'auto'
        })
        // this ul will now be shrink-wrapped to longest li due to position:absolute
        // so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer
        .end().end()[0].clientWidth / fontsize;
        // add more width to ensure lines don't turn over at certain sizes in various browsers
        emWidth += o.extraWidth;
        // restrict to at least minWidth and at most maxWidth
        if (emWidth > o.maxWidth)    { emWidth = o.maxWidth; }
        else if (emWidth < o.minWidth)  { emWidth = o.minWidth; }
        emWidth += 'em';
        // set ul to width in ems
        $ul.css('width',emWidth);
        // restore li floats to avoid IE bugs
        // set li width to full width of this ul
        // revert white-space to normal
        $LIs.css({
          'float' : liFloat,
          'width' : '100%',
          'white-space' : 'normal'
        })
        // update offset position of descendant ul to reflect new width of parent
        .each(function(){
          var $childUl = $('>ul',this);
          var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right';
          $childUl.css(offsetDirection,emWidth);
        });
      });

    });
  };
  // expose defaults
  $.fn.supersubs.defaults = {
    minWidth: 9, // requires em unit.
    maxWidth: 25, // requires em unit.
    extraWidth: 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values
  };

})(jQuery); // plugin code ends;
/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);;
/* Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version 2.1.2
 */
(function(a){a.fn.bgiframe=(a.browser.msie&&/msie 6\.0/i.test(navigator.userAgent)?function(d){d=a.extend({top:"auto",left:"auto",width:"auto",height:"auto",opacity:true,src:"javascript:false;"},d);var c='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+d.src+'"style="display:block;position:absolute;z-index:-1;'+(d.opacity!==false?"filter:Alpha(Opacity='0');":"")+"top:"+(d.top=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+'px')":b(d.top))+";left:"+(d.left=="auto"?"expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+'px')":b(d.left))+";width:"+(d.width=="auto"?"expression(this.parentNode.offsetWidth+'px')":b(d.width))+";height:"+(d.height=="auto"?"expression(this.parentNode.offsetHeight+'px')":b(d.height))+';"/>';return this.each(function(){if(a(this).children("iframe.bgiframe").length===0){this.insertBefore(document.createElement(c),this.firstChild)}})}:function(){return this});a.fn.bgIframe=a.fn.bgiframe;function b(c){return c&&c.constructor===Number?c+"px":c}})(jQuery);;
/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

(function($){
  $.fn.superfish = function(op){
    var sf = $.fn.superfish,
      c = sf.c,
      $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
      over = function(){
        var $$ = $(this), menu = getMenu($$);
        clearTimeout(menu.sfTimer);
        $$.showSuperfishUl().siblings().hideSuperfishUl();
      },
      out = function(){
        var $$ = $(this), menu = getMenu($$), o = sf.op;
        clearTimeout(menu.sfTimer);
        menu.sfTimer=setTimeout(function(){
          o.retainPath=($.inArray($$[0],o.$path)>-1);
          $$.hideSuperfishUl();
          if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
        },o.delay);
      },
      getMenu = function($menu){
        var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
        sf.op = sf.o[menu.serial];
        return menu;
      },
      addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };

    return this.each(function() {
      var s = this.serial = sf.o.length;
      var o = $.extend({},sf.defaults,op);
      o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
        $(this).addClass([o.hoverClass,c.bcClass].join(' '))
          .filter('li:has(ul)').removeClass(o.pathClass);
      });
      sf.o[s] = sf.op = o;

      $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
        if (o.autoArrows) addArrow( $('>a:first-child',this) );
      })
      .not('.'+c.bcClass)
        .hideSuperfishUl();

      var $a = $('a',this);
      $a.each(function(i){
        var $li = $a.eq(i).parents('li');
        $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
      });
      o.onInit.call(this);

    }).each(function() {
      var menuClasses = [c.menuClass];
      if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
      $(this).addClass(menuClasses.join(' '));
    });
  };

  var sf = $.fn.superfish;
  sf.o = [];
  sf.op = {};
  sf.IE7fix = function(){
    var o = sf.op;
    if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
      this.toggleClass(sf.c.shadowClass+'-off');
    };
  sf.c = {
    bcClass: 'sf-breadcrumb',
    menuClass: 'sf-js-enabled',
    anchorClass: 'sf-with-ul',
    arrowClass: 'sf-sub-indicator',
    shadowClass: 'sf-shadow'
  };
  sf.defaults = {
    hoverClass: 'sfHover',
    pathClass: 'overideThisToUse',
    pathLevels: 1,
    delay: 800,
    animation: {opacity:'show'},
    speed: 'normal',
    autoArrows: true,
    dropShadows: true,
    disableHI: false, // true disables hoverIntent detection
    onInit: function(){}, // callback functions
    onBeforeShow: function(){},
    onShow: function(){},
    onHide: function(){}
  };
  $.fn.extend({
    hideSuperfishUl : function(){
      var o = sf.op,
        not = (o.retainPath===true) ? o.$path : '';
      o.retainPath = false;
      var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
          .find('>ul').hide().css('visibility','hidden');
      o.onHide.call($ul);
      return this;
    },
    showSuperfishUl : function(){
      var o = sf.op,
        sh = sf.c.shadowClass+'-off',
        $ul = this.addClass(o.hoverClass)
          .find('>ul:hidden').css('visibility','visible');
      sf.IE7fix.call($ul);
      o.onBeforeShow.call($ul);
      $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
      return this;
    }
  });
})(jQuery);;
/*
 * sf-Touchscreen v1.0b - Provides touchscreen compatibility for the jQuery Superfish plugin. - LAST UPDATE: MARCH 23rd, 2011
 *
 * Developer's notes:
 * Built as a part of the Superfish project for Drupal (http://drupal.org/project/superfish) 
 * Found any bug? have any cool ideas? contact me right away! http://drupal.org/user/619294/contact
 *
 * jQuery version: 1.3.x or higher.
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
*/

(function($){
  $.fn.sftouchscreen = function() {
    // Return original object to support chaining.
    return this.each( function() {
      // Select hyperlinks from parent menu items.
      $(this).find('li > ul').closest('li').children('a').each( function() {
	    var $item = $(this);
        // No .toggle() here as it's not possible to reset it.
        $item.click( function(event){
	      // Already clicked? proceed to the URI.
          if ($item.hasClass('sf-clicked')) {
            var $uri = $item.attr('href');
            window.location = $uri;
          }
          else {
            event.preventDefault();
            $item.addClass('sf-clicked');
          }
        }).closest('li').mouseleave( function(){
          // So, we reset everything.
          $item.removeClass('sf-clicked');
        });
	  });
    });
  };
})(jQuery);;
/*
* Supposition v0.2 - an optional enhancer for Superfish jQuery menu widget - LAST UPDATE: MARCH 23rd, 2011
*
* Copyright (c) 2008 Joel Birch - based mostly on work by Jesse Klaasse and credit goes largely to him.
* Special thanks to Karl Swedberg for valuable input.
* 
* Dec 28th, 2010 - Modified for the Superfish project for Drupal (http://drupal.org/project/superfish)
*
* jQuery version: 1.3.x or higher.
*
* Dual licensed under the MIT and GPL licenses:
* 	http://www.opensource.org/licenses/mit-license.php
* 	http://www.gnu.org/licenses/gpl.html
*/

(function($){
  $.fn.supposition = function(){
    var $w = $(window), /*do this once instead of every onBeforeShow call*/
    _offset = function(dir) {
      return window[dir == 'y' ? 'pageYOffset' : 'pageXOffset']
      || document.documentElement && document.documentElement[dir=='y' ? 'scrollTop' : 'scrollLeft']
      || document.body[dir=='y' ? 'scrollTop' : 'scrollLeft'];
    },
    onHide = function(){
      this.css({Top:'',Right:'',Bottom:'',Left:''});
    },
    onBeforeShow = function(){
      this.each(function(){
        var $u = $(this);
        $u.css('display','block');
        var menuWidth = $u.width(),
        menuParentWidth = $u.closest('li').outerWidth(true),
        menuParentLeft = $u.closest('li').offset().left,
        totalRight = $w.width() + _offset('x'),
        menuRight = $u.offset().left + menuWidth,
        exactMenuWidth = (menuRight > (menuParentWidth + menuParentLeft)) ? menuWidth - (menuRight - (menuParentWidth + menuParentLeft)) : menuWidth;  
        if ($u.parents('.sf-js-enabled').hasClass('rtl')) {
          if (menuParentLeft < exactMenuWidth) {
            $u.css('left', menuParentWidth + 'px');
            $u.css('right', 'auto');
          }
        }
        else {
          if (menuRight > totalRight && menuParentLeft > menuWidth) {
            $u.css('right', menuParentWidth + 'px');
            $u.css('left', 'auto');
          }
        }
        var windowHeight = $w.height(),
        offsetTop = $u.offset().top,
        menuParentHeight = $u.parent().outerHeight(true),
        menuHeight = $u.height(),
        baseline = windowHeight + _offset('y');
        var expandUp = ((offsetTop + menuHeight > baseline) && (offsetTop > menuHeight));
        if (expandUp) {
          $u.css('bottom', menuParentHeight + 'px');
          $u.css('top', 'auto');
        }
        $u.css('display','none');
      });
    };

    return this.each(function() {
    var o = $.fn.superfish.o[this.serial]; /* get this menu's options */

    /* if callbacks already set, store them */
    var _onBeforeShow = o.onBeforeShow,
    _onHide = o.onHide;

    $.extend($.fn.superfish.o[this.serial],{
    onBeforeShow: function() {
    onBeforeShow.call(this); /* fire our Supposition callback */
    _onBeforeShow.call(this); /* fire stored callbacks */
    },
    onHide: function() {
    onHide.call(this); /* fire our Supposition callback */
    _onHide.call(this); /* fire stored callbacks */
    }
    });
    });
  };
})(jQuery);;

