// ###############################################
//
// AUTHOR: Nick LaPrell (http://nick.laprell.org)  
//
// Project Home: http://code.google.com/p/ezcookie/
//
// ###############################################

(function(jQuery){
  
  // Default options
  dOptions = {
    expires : 365,
    domain : '',
    secure : false,
    path : '/'
  }

  // Returns the cookie or null if it does not exist.
  jQuery.cookie = function(cookieName) {
    var value = null;
    if(document.cookie && document.cookie != ''){
      var cookies = document.cookie.split(';');
      for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        if (cookie.substring(0, cookieName.length + 1) == (cookieName + '=')) {
          value = decodeURIComponent(cookie.substring(cookieName.length + 1));
          break;
        }
      }
    }
	try {
		// Test for a JSON string and return the object
		return JSON.parse(value);
	} catch(e){
		// or return the string
    	return value;
	}
  }
  
  jQuery.subCookie = function(cookie,key){
  	var cookie = jQuery.cookie(cookie);
    if(!cookie || typeof cookie != 'object'){return null;}
	return cookie[key];
  }
  
  // Write the defined value to the given cookie
  jQuery.setCookie = function(cookieName,cookieValue,options){
    // Combine defaults and passed options, if any
    var options = typeof options != 'undefined' ? jQuery.extend(dOptions, options) : dOptions;
    // Set cookie attributes based on options
    var path = '; path=' + (options.path);
    var domain = '; domain=' + (options.domain);
    var secure = options.secure ? '; secure' : '';
	if (cookieValue && (typeof cookieValue == 'function' || typeof cookieValue == 'object')) {
		cookieValue = JSON.stringify(cookieValue);
	}
	cookieValue = encodeURIComponent(cookieValue);
    var date;
    // Set expiration
    if (typeof options.expires == 'number') {
      date = new Date();
      date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
    } else {
      date = options.expires;
    }
    var expires = '; expires=' + date.toUTCString();
    // Write the cookie
    document.cookie = [cookieName, '=', cookieValue, expires, path, domain, secure].join('');
  }
  
  jQuery.setSubCookie = function(cookie,key,value,options){
  	var options = typeof options != 'undefined' ? jQuery.extend(dOptions, options) : dOptions;
	var existingCookie = jQuery.cookie(cookie);
	var cookieObject = existingCookie && typeof existingCookie == 'object' ? existingCookie : {};
	cookieObject[key] = value;
	jQuery.setCookie(cookie,cookieObject,options);
  }
  
  jQuery.removeSubCookie = function(cookie,key){
  	var cookieObject = jQuery.cookie(cookie);
	if(cookieObject && typeof cookieObject == 'object' && typeof cookieObject[key] != 'undefined'){
		delete cookieObject[key];
		jQuery.setCookie(cookie,cookieObject);
	}
  }

  jQuery.removeCookie = function(cookie){
    jQuery.setCookie(cookie,'',{expires:-1});
  }

  jQuery.clearCookie = function(cookie){
    jQuery.setCookie(cookie,'');
  }
  
})(jQuery);

// Begin minified json2.js library from json.org
// http://www.json.org/js.html
if(!this.JSON){this.JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*jQuery/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());jQuery.noConflict();// jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
// http://jquery.thewikies.com/swfobject
(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);//Search Functions

function clearSearch() {
	jQuery('#sitesearch').css("color", "#000");
	if (jQuery('#sitesearch').val() == "Search") {
		jQuery('#sitesearch').val("");
	}
}

function resetSearch() {
	jQuery('#sitesearch').css("color", "#666");
	if (jQuery('#sitesearch').val() == "") {
		jQuery('#sitesearch').val("Search");
	}
}

jQuery(document).ready(function() {

	//set hover class for anything
	jQuery('#mainnav #navigation li').hover(function() {
		jQuery(this).addClass('hover');
	}, function() {
		jQuery(this).removeClass('hover');
	});

	jQuery("a.lightwindow").fancybox({
		'titlePosition'	: 'inside'
	});

	jQuery('#tabbed-content').tabs({
	    fxFade: true,
	    fxSpeed: 'fast',
	    fxAutoHeight: true,
	    selected: 1
	}); 

	// Hiding and showing items
	jQuery(".hider").css("display", "none");
	jQuery(".list-item").css("cursor", "pointer");

	jQuery(".list-item").click(function() {
		jQuery(this).children().children(".hider").slideToggle();
	});

	jQuery(".list-link").click(function(){
		var listLinkLocation = jQuery(this).find("a").attr("href"); 
		window.href(listLinkLocation);
		return false;
	});

	jQuery(".list-item").hover(
  		function () {
			jQuery(this).css("background-color", "#eee");
  		},
  		function () {
			jQuery(this).css("background-color", "inherit");
		}
	);

	if (jQuery("#productshowcase_product1").length != 0) {
		productswitch("#productshowcase_product1", "#productshowcase_nav1");
	};

	jQuery("#onstart_popup").fancybox({	'width'				: 800,
						'height'			: 825,
						'padding'			: 0,
						'autoScale'			: false,
						'transitionIn'			: 'none',
						'transitionOut'			: 'none',
						'type'				: 'iframe'
	});

	function productswitch($selected, $nav) {
		jQuery(".productshowcase_product").css("display", "none");
		jQuery("#productshowcase_nav a").removeClass("active");

		jQuery($selected).css("display", "block");
		jQuery($nav).addClass("active");
	};

	jQuery('#quick-subscribe').click(function(){ });	

	jQuery("#quick-subscribe").submit(function(event) {
		event.preventDefault();
		jQuery('#subscribe_successful').hide();
		jQuery('#subscribe_unsuccessful').hide();

		var ErrorCount       = 0;
		var Email            = jQuery('input[name=email]');
	
		if (Email.val()=='') {
			Email.addClass('missing');
			ErrorCount++; 
		} else Email.removeClass('missing');

		if (!checkEmail(Email.val())) {
			Email.parent().addClass('valid');
			ErrorCount++; 
		} else Email.removeClass('valid');

		if ( ErrorCount > 0 ) {
			alert('Please enter a valid email address');
			return false;
		}

		var data = '?firstname=%20' 
			+ '&lastname=%20'
			+ '&email=' + Email.val() 
			+ '&company=%20' 
			+ '&phone=%20' 
			+ '&jobtitle=%20'
			+ '&country=%20'
			+ '&state=%20'
			+ '&industry=IOC'
			+ '&ajax=1'
			+ '&bandwidth=1'
			+ '&regional=0'
			;
		jQuery.ajax({

			url: "/bandwidth/subscribe/subscribe.php",	
			type: "GET",
			dataType: 'json',
			data: data,		
			
			cache: false,

			success: function(parsed_response) {
				alert('complete');
				alert(parsed_response.code);
				alert(parsed_response.message);

				if (parsed_response.code != 0) {
					var errorMsg = '';
					if (parsed_response.code > 200) {
						errorMsg = 'An error has occured.';
					}
					else {
						errorMsg = parsed_response.message;
					}
			
					jQuery('#subscribe_unsuccessful').replaceWith(errorMsg);
					jQuery('#subscribe_unsuccessful').fadeIn(500);
				}
				else {
					jQuery('#subscribe_successful').fadeIn(500);
				}
			}		
		});

		jQuery('#bandwidth-formfield').hide(500);
		return false;
	});

	jQuery('#hubspot-submit').click(function(){	});	

	jQuery("#hubspot-form").submit(function(event) {
		event.preventDefault();
		
		var ErrorCount		= 0;
		var formName 		= jQuery('input[name=formName]');
		var FirstName		= jQuery('input[name=FirstName]');
		var LastName		= jQuery('input[name=LastName]');
		var Email 		= jQuery('input[name=Email]');
		var Company		= jQuery('input[name=Company]');
		var Phone		= jQuery('input[name=Phone]');
		var City 		= jQuery('input[name=City]');
		var Code		= jQuery('input[name=Code]');
		var Type		= jQuery('select[name=Type]');
		var Protocol		= jQuery('input[name=Protocol]');
		var Message		= jQuery('textarea[name=Message]');
		var MessageValue 	= ' ';
		
		if (FirstName.val()=='') {
			FirstName.addClass('missing');
			ErrorCount++; 
		} else FirstName.removeClass('missing');

		if (LastName.val()=='') {
			LastName.addClass('missing');
			ErrorCount++; 
		} else LastName.removeClass('missing');

		if (Email.val()=='') {
			Email.addClass('missing');
			ErrorCount++; 
		} else Email.removeClass('missing');

		if (!checkEmail(Email.val())) {
			Email.parent().addClass('valid');
			ErrorCount++; 
		} else Email.removeClass('valid');
		
		/* Stop on Errors */
		if ( ErrorCount > 0 ) {
			return false;
		}

		if (formName.val()=='Managed-Network-Service-Locator') {
			MessageValue = "Product Type: " + Type.val() + "\r\nProtocols Supported: " + Protocol.val() + "\r\nMessage: \n" + Message.val();		
		};

		if (MessageValue==' ') {
			MessageValue= Message.val();
		};	
		
		var data = 'form=' + formName.val() 
			+ '&FirstName=' + FirstName.val() 
			+ '&LastName=' + LastName.val() 
			+ '&Email=' + Email.val() 
			+ '&Company='  + Company.val() 
			+ '&Phone='  + Phone.val() 
			+ '&City=' + City.val()
			+ '&ZipCode=' + Code.val()
			+ '&Message=' + MessageValue
			;

		jQuery.ajax({
			url: "/_include/php/form.php",	
			type: "GET",
			data: data,		

			cache: false,

			success: function(html) {				

				if (html==1) {					
					window.location =  document.location.pathname + "?user=" + Email.val() + "&ts=194885";
				} else alert('Sorry, unexpected error. Please try again later.');				
			}		
		});
		_gaq.push(['_trackEvent', 'Landing-Page', 'To Lead', jQuery("h1").html() ]);
		//cancel the submit button default behaviours
		return false;
		});

	function UnsubscribeAll(){
		jQuery('#unsubscribe_successful').hide();
		jQuery('#unsubscribe_unsuccessful').hide();

		var ErrorCount       = 0;
		var Email            = jQuery('input[name=user_email]');

		if (!checkEmail(Email.val())) {
			Email.parent().addClass('valid');
			ErrorCount++; 
		} else Email.removeClass('valid');

		if ( ErrorCount > 0 ) {
			alert('Please enter a valid email address');
			return false;
		} else {
			jQuery('#progress').fadeIn(500);

		var data = '?firstname=%20' 
			+ '&lastname=%20'
			+ '&email=' + Email.val() 
			+ '&company=%20' 
			+ '&phone=%20' 
			+ '&jobtitle=%20'
			+ '&country=%20'
			+ '&state=%20'
			+ '&industry=IOC'
			+ '&ajax=1'
			+ '&bandwidth=1'
			+ '&regional=0'
			;
			
		var data = 'user_email=' + Email.val() + '&ajax=1';
		jQuery.ajax({
			url: "/bandwidth/unsubscribe/unsubscribe.php",	
			type: "GET",
			dataType: 'json',
			data: data,		
			
			cache: false,

			success: function(parsed_response) {
				jQuery("#progress").fadeOut(500);

				alert('complete');
				alert(parsed_response.code);
				alert(parsed_response.message);

				if (parsed_response.code != 0) {
					jQuery('#unsubscribe_unsuccessful').fadeIn(500);
					alert("There has been a problem with the system, please email marketing@btisystems.com with the title Unsubscribe.");
				} else {
					jQuery('#unsubscribe_successful').fadeIn(500);
				}
			}		

		});
	}
}

});
