/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 * API rewrite by Lauris Buk�is-Haberkorns
 * IE8 support added by Jonathan Francis (unpublished)
 */

(function($) {

function History() {
	this._curHash = '';
	this._callback = function(hash){};
}

$.extend(History.prototype, {

	init: function(callback) {
		this._callback = callback;
		this._curHash = location.hash;

		if($.browser.msie && $.browser.version < 8) {
			// To stop the callback firing twice during initilization if no hash present
			if (this._curHash == '') {
				this._curHash = '#';
			}

			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var iframe = $("#jQuery_history")[0].contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = this._curHash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			this._historyBackStack = [];
			this._historyBackStack.length = history.length;
			this._historyForwardStack = [];
			this._isFirst = true;
			this._dontCheck = false;
		}
		this._callback(this._curHash.replace(/^#/, ''));
		setInterval(this._check, 100);
	},

	add: function(hash) {
		// This makes the looping function do something
		this._historyBackStack.push(hash);

		this._historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this._isFirst = true;
	},

	_check: function() {
		if($.browser.msie && $.browser.version < 8) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != $.history._curHash) {

				location.hash = current_hash;
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));

			}
		} else if ($.browser.safari) {
			if (!$.history._dontCheck) {
				var historyDelta = history.length - $.history._historyBackStack.length;

				if (historyDelta) { // back or forward button has been pushed
					$.history._isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) $.history._historyForwardStack.unshift($.history._historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) $.history._historyBackStack.push($.history._historyForwardStack.shift());
					}
					var cachedHash = $.history._historyBackStack[$.history._historyBackStack.length - 1];
					if (cachedHash != undefined) {
						$.history._curHash = location.hash;
						$.history._callback(cachedHash);
					}
				} else if ($.history._historyBackStack[$.history._historyBackStack.length - 1] == undefined && !$.history._isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						$.history._callback(document.URL.split('#')[1]);
					} else {
						$.history._callback('');
					}
					$.history._isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != $.history._curHash) {
				$.history._curHash = current_hash;
				$.history._callback(current_hash.replace(/^#/, ''));
			}
		}
	},

	load: function(hash) {
		var newhash;

		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		this._curHash = newhash;

		if ($.browser.msie && $.browser.version < 8) {
			var ihistory = $("#jQuery_history")[0]; // TODO: need contentDocument?
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			// Manually keep track of the history values for Safari
			this.add(hash);

			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {$.history._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	}
});

$(document).ready(function() {
	$.history = new History(); // singleton instance
});

})(jQuery);



(function($) {
	$.fn.customFadeIn = function(speed, callback) {
		$(this).css('background-color','#FFF').fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).css('background-color','#FFF').fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
})(jQuery);

globalCarousel = '';
visibleItem = -1;
pageLoad = true;
var AutoScrollTimer = 8;
$(function() {
  $("#carousel").jcarousel({
    initCallback: csCarouselInitCallback,
    itemVisibleInCallback: {onBeforeAnimation: csCarousel_itemVisibleInCallback},
    buttonNextHTML: null,
    buttonPrevHTML: null,
    scroll: 1,
    visible: 1,
    animation: "slow",
    size: 6,
    wrap: "circular",
    auto: AutoScrollTimer
  });

  //re-write the href's in the anchor tag.
  $(".jcarousel-control a").each(function() {
    var curr_href = $(this).attr("href");
    $(this).attr("href", "#"+curr_href);
  });

   // Initialize the history controler
  $.history.init(historyCallback);
  init_expandable_menus();
  
});

function csCarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
  carousel.remove(i);
}

/**
 * When the selected item is visible in the carousel, this function is called.
 */
function csCarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
  var element = carousel.get(i);
  var id = element.find("div").attr("id").split('-');
  $(".showcase-subheader-item.visible").removeClass("visible").customFadeOut("slow");
  $(".showcase-subheader-item-nid-" + id[1]).addClass("visible").customFadeIn("slow");
  $(".control-item a.active").removeClass("active");
  $(".control-item-primary-nid-"+id[1]+" a:first").addClass("active");
  var next = $(".control-item-primary").eq(i+1);
}
/**
 * BACKGROUND: no-repeat left top;
 * FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://ldev.c-sgroup.com/files/carousel_images/our_products_acrovyn-wall_s.png",sizingMethod="scale");
 * HEIGHT: 25px
*/
function csCarouselInitCallback(carousel, state) {
  globalCarousel = carousel;

  buildCarouselObject(carousel, state);

  // Now on the navigational links, build the click events to effect the carousel.
  $(".control-item a, #node-1507 .carousel-item-links UL A").click(function() {
    var hash = this.href.replace(/^.*#/,'').concat();
    $.history.load(hash);

    return false; //navigationalClick(this, carousel);
  });

  /**
   * This bit of code can be concidered the controler for the extra link added to the front page, titled
   * "Our Products" and also when the mouse hovers over the product overlay links.
   *
   * This codes halts the autoscrolling feature and the timer to hide the product overlays.
   */
  $("#node-1507 .carousel-item-links A,LI#control-item-primary-nid-1507 UL LI.control-item A").mouseover(function() {

				window.clearInterval(globalCarousel.timer);
				globalCarousel.options.auto = 0;
        clearTimeout(initial_product_overlay_fadeout_with_auto_scroll);

  });

}

function buildCarouselObject(carousel, state) {
  // This will select all primary carousel items and build the carousel object.
  // This is done for the auto scroll feature.
  $(".jcarousel-control ul li.control-item-primary").each(function(i){
    var id = $(this).attr("id").split('-');
    var nid = id[4];
    carousel.add(i+1, $(".carousel-pane-nid-" + nid).html() );
  });

  //For some reason, IE 6 was not displaying the first item loaded. So here we
  //simply load it again, and that seems to fix it.
  var id_first = $(".jcarousel-control ul li.control-item-primary").eq(0).attr("id").split('-');
  carousel.add( 1, $(".carousel-pane-nid-" + id_first[4]).html() );
}

/**
 * Whenever a navigational/control item has been clicked, then this function is called.
 */
firstTime = true;
initial_product_overlay_fadeout_with_auto_scroll = '';
function historyCallback(hash) {
  var InitialObjectToDisplay_selector = ".jcarousel-control a[href='#/showcase/our-products']";

  if (hash != '') { // If hash contains a value, then use the hash to slide the carousel and show/hide overlays, etc...
    navigationalClick($(".jcarousel-control a[href='#"+hash+"']"), globalCarousel, true, true);
  } else {
    if (!firstTime) { // Looks like we're viewing the initial load of the homepage and somebody clicked the back button. So display the right content.
      navigationalClick($(InitialObjectToDisplay_selector), globalCarousel, true, true, false);

      //fadeOverlay($(".jcarousel-control a[href='#/showcase/our-products']"), $(".jcarousel-control a[href='#/showcase/our-products']").parent());
      //var theObject = $(".jcarousel-control a:first");
      //navigationalClick(theObject, globalCarousel, false, true);
      //$(".jcarousel-control UL LI UL").customFadeOut('slow');
      //$(".jcarousel-control UL").removeClass("expanded");

    } else { // This code will be exec when the page is initially loaded.
      var jQuery_selectorObj = $(InitialObjectToDisplay_selector);
      fadeOverlay(jQuery_selectorObj, $(jQuery_selectorObj).parent(), true);

      initial_product_overlay_fadeout_with_auto_scroll = setTimeout(function() {
          hideOverlay($(".jcarousel-control a[href='#/showcase/featured-project']"))
      }, AutoScrollTimer*1000);
      
      firstTime = false;

    }
  }
}

function navigationalClick(clickedObj, carousel, overlay, animate, firsttime) {
		var clickedObj_parent = $(clickedObj).parent();
  var id = clickedObj_parent.parent().attr("id").split('-'); // first step of getting the nid
  var nid = id[4];

		if (!firsttime || firsttime == null)
				carousel.options.auto = 0;                                               // Make certain to no longer scroll the content.

  carouselScroll(carousel, clickedObj, animate);                              // Scroll item into view

  $("a.active").removeClass("active");
  $(clickedObj).addClass("active");

  if (overlay) {
    var clickedObj_parent_3 = clickedObj_parent.parent().parent();
    if (clickedObj_parent_3.hasClass("control-item-primary")) {
      fadeOverlay(clickedObj_parent_3.find("A:first"));
    } else {
      fadeOverlay(clickedObj, clickedObj_parent);
    }
  }
  init_expandable_menus()
  return false;
}

function hideOverlay(clickedObj,animate) {
  if (animate == true || animate == null)
    animate = "slow";
  else
    animate = 0;

  var not_clickedObj_parent = $("li.control-item-primary a").not(clickedObj).parent();
  not_clickedObj_parent.find("ul").customFadeOut(animate, function() {
    not_clickedObj_parent.removeClass("expanded");
    not_clickedObj_parent.parent().removeClass("expanded");
  }); // fade out all other sub menus
}

function fadeOverlay(clickedObj, clickedObj_parent, animate) {
  if (animate == true || animate == null)
    animate = "slow";
  else
    animate = 0;

  if (clickedObj_parent == '' || clickedObj_parent === undefined)
    clickedObj_parent = $(clickedObj).parent();

  // If this item is a primary item then look for a child ul to expand
  if( clickedObj_parent.hasClass("control-item-primary") ) {                 // we only want to run the code for the primary menu system

    hideOverlay(clickedObj);

    if( 0 < clickedObj_parent.find("ul").size() ) {  // if there content in the UL container, then we have some new content to display.
      clickedObj_parent.find("ul").customFadeIn(animate); // fade in the content.
      clickedObj_parent.addClass("expanded");
      clickedObj_parent.parent().addClass("expanded");
    }
  }
}


/**
 * This function is designed to scroll/slide to the proper slide in the carousel jQuery Plugin.
 *
 * @param <obj> carousel object - this is the ccarousel that we're modifying.
 * @param <obj> Anchor DOM object - this is the anchor that we're accessing
 *
 */

function carouselScroll(carouselObj, anchorObj, ani) {
  unbind_expandable_menus();
  var scrollTo = jQuery.jcarousel.intval($(".jcarousel-control ul.control LI.control-item").index($(anchorObj).parent())); // Get the index value of the LI item that the anchor (that we clicked on) is contained.
 
	// only calculate the carousel slide if we are changing positions.
	if (scrollTo==visibleItem && visibleItem!= -1) {
    return ;
  }

  var id = $(anchorObj).parent().attr("id").split('-'); // first step of getting the nid
  var nid = id[4];

  var first=0;
	var second=0;

	// Which direction are we going? sliding left or sliding right? This controls the placement of the images into the carousel.
	// It's possible to take out this branch (else).
	if (scrollTo < visibleItem) {
		first = 2;
		second = 1;
	} else {
		first = 1;
		second = 2;
	}

	carouselObj.lock();																		// Don't display the changes in the carousel.
	prev_nid = $(".jcarousel-item[jcarouselindex='"+jQuery.jcarousel.intval(carouselObj.first)+"'] .ntype-carousel-item:first").attr('id').split("-")[1];

 carouselObj.add(first, $(".carousel-pane-nid-" + prev_nid).html());		// this will replace the index (first) with the slide.
	carouselObj.add(second, $(".carousel-pane-nid-" + nid).html());   // this will replace the index (second) with the slide.
	visibleItem = scrollTo;															// Update the global varialbe with what is now the current slide.

	carouselObj.size(2);																	// update the size of the carousel.
	carouselObj.reload();																  // reload the carousel.
	carouselObj.unlock();																	// write all changes to the DOM.
	carouselObj.scroll(first, false);											// scroll to the correct position without animating.
	carouselObj.scroll(second, ani);											// Animate to the clicked position.
	
}

function unbind_expandable_menus() {
  $(".carousel-menu-item-link").unbind("click");
}
function init_expandable_menus() {
  $(".carousel-menu-item-link").mouseover(function() {
    $(this).children("ul.menu").show();
  })
  .mouseout(function() {
    $(this).children("ul.menu").hide();
  });
		$(".carousel-menu-item-link > a").click( function() {
    return false;
  });
		$("#node-1507 .carousel-item-links UL A").click(function() {
    var hash = this.href.replace(/^.*#/,'').concat();
    $.history.load(hash);

    return false; //navigationalClick(this, carousel);
  });
}