﻿/*
 * primary JavaScript file for SIFCO
 * requires: jQuery.js (written and tested against jQuery version 1.4.2)
 * requires: bgc.js
 */
 
// create CSS hook for JS-enabled clients
if ($.browser.msie) {
	$("html").addClass("js ie");
} else {
	$("html").addClass("js");
}

// prevent background image flicker in IE
try {
	if (!window.opera) document.execCommand("BackgroundImageCache", false, true);
} catch(err) {};

// GA initialization and pageview tracking
BGC.track.init("UA-5870535-13");
BGC.track();

String.prototype.cleanLabel = function () {
	return this.replace(/\W/g, "");
};

var Sifco = Sifco || {};

Sifco.init = function () {
	// keep background images aligned (only webkit seems to require this)
	function centerBackground () {
		var x = Math.max( Math.floor(BGC.getViewportSize().x / 2), 487);
		this._body = this._body || $('body');
		this._wrapper = this._wrapper || $('#wrapper');
		this._ft = this._ft || $('#ft > div');
		this._body.css({backgroundPosition: (x - 600) + 'px 50px'});
		this._wrapper.css({marginLeft: x - 487});
		this._ft.css({marginLeft: x - 475});
	}
	
	$(window)
		.bind("resize", centerBackground)
		.triggerHandler("resize");
		
	// product overlay
	Sifco.UI.Overlay.init({
		type: "iframe",
		id: "overlay-product",
		overlayStyle: {},
		iframeWidth: 472,
		iframeHeight: 460,
		src: null
	});
	
	// contact us overlay
	Sifco.UI.Overlay.init({
		type: "iframe",
		id: "overlay-contactus",
		overlayStyle: {},
		iframeWidth: 480,
		iframeHeight: 460,
		src: null,
		modal: true
	});
		
	// tracking
	Sifco.Tracking.init();
	
	// forms
	Sifco.Forms.init();
};

Sifco.Forms = {
	init: function () {
		$(".hint").hint(); // apply form field hints
	}
};

Sifco.Tracking = {
	init: function () {
		// class-based GA tracking hooks
		// link tracking (finds and tracks links with class="track category|action|label" applied)
		$("a.track").click(function (e) {
			var ev = getEventString(this.className), target = null, callback = null, href = null;
			if (ev) {
				target = this.target;
				if ( !this.className.match(/overlay/) && ( !target || target.match(/^_(self)|(top)$/i) ) ) {
					href = $(e.target).closest("a")[0].href;
					callback = function () {
						if ( target.match(/^_top$/i) ) {
							top.location.href = href;
						} else {
							location.href = href;
						}
					};
					e.preventDefault();
				}
				BGC.track(ev, callback);
			}
		});
		
		// form view/submit "action" (virtual pageview) tracking
		$("form.track").each(function () {
			var ev = getEventString(this.className).replace(/\|/g, "/");
			if (ev) {
				BGC.track(ev + "/view");
				$(this).submit(function (e) {
					if (Page_IsValid) { // only track the submit action if the .NET validation routine passed
						BGC.track(ev + "/submit");
					}
				});
			}
		});
		
		function getEventString (s) {
			var ev = "";
			s = s.split(" ");
			$.each(s, function () {
				if (this.indexOf("|") > -1) {
					ev = this.toString();
					return;
				}
			});
			return ev;
		}
	}
};

Sifco.UI = {
	Overlay: {
		init: function (options) {
			var $o = $("#" + options.id);
			if ( !$o.length ) { // create the overlay content container if it doesn't exist already
				$o = $('<div id="' + options.id + '" class="overlay-window"></div>').appendTo("body");
			}
			
			$o.empty();
			
			$o.append('<a href="#" class="jqmClose">Close</a>');
			$o.append('<div class="content"></div>');
			
			if (options.overlayStyle) {
				$o.css(options.overlayStyle);
				$o.css({display: "block"}); // element must be "block" to get the offsetWidth
				if (options.overlayStyle.centerH) {
					$o.css({marginLeft: -($o[0].offsetWidth / 2)}); // center the overlay
				}
				if (options.overlayStyle.centerV) {
					$o.css({marginTop: -($o[0].offsetHeight / 2)}); // center the overlay
				}
				$o.css({display: "none"});
			}
			
			$o.jqm({
				modal: options.modal || false,
				//trigger: options.trigger, see addTrigger()
				overlay: 30,
				onShow: loadContent,
				onHide: function (hash) {
					$o.fadeOut("fast", function () {
						$o.children(".content").empty();
						hash.o.remove();
						//$.scrollTo(0, 0);
						// publish "overlayHide" notification
						$o.trigger("overlayHide");
						// tracking
						BGC.track("overlay|" + $o.attr("id") + "|close");
					});
				}
			});
			
			Sifco.UI.Overlay.addTrigger(null, options.id);
			
			function loadContent (hash) {
				var $t = $(hash.t),
					vp = BGC.getViewportSize();
				$t.pos = BGC.getElemPosition($t[0]);
				$t.w = $t.width();
				
				switch (options.type) {
					case "iframe":
						var src = options.src || $t.attr("href"),
							$i = $('<iframe src="' + src + '" frameborder="0" marginwidth="0" marginheight="0"></iframe>').appendTo( $o.children(".content") );
						if (options.iframeWidth) {
							$i.css({width: options.iframeWidth});
						}
						if (options.iframeHeight) {
							$i.css({height: options.iframeHeight, minHeight: options.iframeHeight});
						}
						$i[0].src = $i[0].src; // fixes cached-iframe issues in chrome/IE ?!?
						$(document).bind("iframeLoad", resizeOverlay);
						break;
					case "inline":
						$( options.src /*.clone(true)*/ ).appendTo( $o.children(".content") ).show();
						break;
				}
				
				if (!options.overlayStyle.centerV) {
					//$o.css({top: $t.pos.y});
					$o.css({top: BGC.getScrollOffset().y + 40});
				}
				
				if (!options.overlayStyle.centerH) {
					if ($t.pos.x + $t.w > vp.x / 2) {
						$o.css({left: "auto", right: vp.x - $t.pos.x - $t.w});
					} else {
						$o.css({left: $t.pos.x + $t.w});
					}
					
				}

				$o.fadeIn("fast");
				
				if (options.overlayStyle.centerV) {
					$.scrollTo($o, 400, {offset: -30});
				}
				
				// publish "overlayShow" notification
				$o.trigger("overlayShow");
				
				// tracking
				BGC.track("overlay|" + $o.attr("id") + "|open");
			}
			
			function resizeOverlay (e, height) {
				$o.find(".content > iframe").andSelf().animate({height: Math.max(options.iframeHeight, height)}, 600);
			}
		},
		
		addTrigger: function (e, id) {
			if (id) {
				var $t = $("." + id).removeClass("overlay-trigger");
				$("#" + id).jqmAddTrigger($t)
			} else {
				$(e.target).find(".overlay-trigger").each(function () {
					id = $(this).removeClass("overlay-trigger")[0].className;
					$("#" + id).jqmAddTrigger(this);
				});
			}
		}
	}	
};



/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);


/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
      // Hack to allow the ASP.NET link buttons to work (http://softwareblog.morlok.net/2009/02/23/labelify-for-aspnet-11/)
	  $("a[href^=javascript:__doPostBack]").click(remove);
    }
  });
};

})(jQuery);



