jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = 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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){

    // to store it in a variable
    var s = new String();
    s = String(window.location);
    //var locStr = loc.toString():
  var finger = s.indexOf('/uk/products/location-intelligence/');
    var loc = window.location;







	swapValues = [];
    $(".swap").each(function(i){swapValues[i] = $(this).val();
        $(this).focus(function(){if ($(this).val() == swapValues[i]) {$(this).val("");}}).blur(function(){ if ($.trim($(this).val()) == "") {$(this).val(swapValues[i]);}});
	});
	
		//Handle offsite links
	$('#content a').filter(function() {
		var theHref = this;
		if (theHref.hostname && theHref.hostname !== location.hostname) {
			$(theHref).not(".noAutoIcon").addClass("offSite");
			$(theHref).not(".noAutoLink").bind('click keypress', function(event) {
				var code=event.charCode || event.keyCode;
				if (!code || (code && code == 13)) {
					if(pageTracker){
						var fixedLink = this.href;
						fixedLink = fixedLink.replace(/https?:\/\/(.*)/,"$1");
						fixedLink = '/outgoing/' + fixedLink;
						pageTracker._trackPageview(fixedLink);
					};
				};
			});
		};
	});
	
		//Automatic PDF file handling
	$("a[href$='.pdf']:not(.noAutoIcon)").addClass("pdf");
	$("a[href$='.pdf']").bind('click keypress', function(event) {
		var code=event.charCode || event.keyCode;
		if (!code || (code && code == 13)) {
			var fixedLink = "/downloaded-files/pdf/" + this.pathname;
			_gaq.push(['_trackEvent','Links','PDF',this.pathname]);
			_gaq.push(['_trackPageview',fixedLink]);
		};
	});

/*	//Automatic PDF file handling
	$("a[@href$='.pdf']:not(.noAutoIcon)").addClass("pdf");
	$("a[@href$='.pdf']").bind('click keypress', function(event) {
		var code=event.charCode || event.keyCode;
		if (!code || (code && code == 13)) {
			if(pageTracker){
				var fixedLink = "/downloaded-files/pdf/" + this.pathname;
				pageTracker._trackPageview(fixedLink);
			};
		};
	});*/
	
	//Email to a Friend function
	
			
	

	
	
	
	//Track Downloads
	$("a.download").bind('click keypress', function(event) {
		var code=event.charCode || event.keyCode;
		if (!code || (code && code == 13)) {
			if(pageTracker){
				var fixedLink = "/downloaded-files/misc/" + this.pathname;
				pageTracker._trackPageview(fixedLink);
			};
		};
	});
	
	//colored OL
	$('ol li').wrapInner('<span class="olcontent"></span>').addClass('olcolor');
	
	//Nav
	$('ul#main-nav li').hover(function(){
		$(this).addClass('active');	
	},function(){
		$(this).removeClass('active');
	});
	
	$("body#supportDownloads ul:not(:has(li))").append("<li>No downloads in this category.</li>");
	
	var limit = 2;//desired number - 1;
	$("ul",$("#portlets")).each(function(){
		if($(this).parent("div").attr("id") == "multimedia"){limit = limit - 1;}
		currClass = $(this).parent("div").attr("class");
		//if(currClass != "standard"){
			var totalLi = $(this).children("li");
			var childCount = totalLi.size();
			if(childCount <= limit){
				$(this).next("a.all").addClass("all-hide");
			}else{
				for(i=0; i<childCount; i++){
					if(i > limit){
						$(totalLi[i]).addClass("hide");
					}
				}
			}
		//}
		if($(this).parent("div").attr("id") == "multimedia"){limit = limit + 1;}
	});
	
	$("a.all", $("#portlets")).each(function(){
		if($(this).prev("ul").parent("div").attr("id") == "multimedia"){limit = limit - 1;}
		count = $(this).prev("ul").children().length;
		if(count <= (limit+1)){$(this).addClass("hide");}
		if($(this).prev("ul").parent("div").attr("id") == "multimedia"){limit = limit + 1; }	 
		$(this).toggle(function(){
			$(this).addClass("less");
			$(this).children("span.toggle").text("Less");
			$(this).prev("ul").children("li.hide").removeClass("hide");
			return false;
		},function(){
			if($(this).prev("ul").parent("div").attr("id") == "multimedia"){limit = limit - 1;}
			$(this).removeClass("less");
			$(this).children("span.toggle").text("All");
			var totalLi = $(this).prev("ul").children("li");
			var childCount = totalLi.size();
			for(i=0; i<childCount; i++){
				if(i > limit){
					$(totalLi[i]).addClass("hide");
				}
			}
			if($(this).prev("ul").parent("div").attr("id") == "multimedia"){limit = limit + 1; }
			return false;
		});
		
	});
	
	//add left border
	$("table.standard thead th:first").addClass("lb");
	
	whereitat = window.location + "";
	splitUrl = whereitat.split("/");
	if(splitUrl[3] == "About"){
		$("li#about-pbbi").addClass("current");
	}else if(splitUrl[3] == "Communities"){
		$("li#communities").addClass("current");
	}else if(splitUrl[3] == "Partners"){
		$("li#partners").addClass("current");
	}else if(splitUrl[3] == "Products"){
		$("li#products").addClass("current");
	}else if(splitUrl[3] == "Resources"){
		$("li#resources").addClass("current");
	}else if(splitUrl[3] == "Solutions"){
		$("li#solutions").addClass("current");
	}else if(splitUrl[3] == "Support"){
		$("li#support").addClass("current");
	}else if(splitUrl[3] == "index.html"){
		$("li#home").addClass("current");	
	}
	
	$("a.flash-pop").click(function(){
		var rel = $(this).attr("rel");
		$('#showFlash').css('display', 'block').flash({ swf: '/uk/flash/Player.swf', height: 400, width:550, params: { wmode:'transparent'}, flashvars:{flv:rel}}); 
		return false;
	});
	
	
	$("#content a[href$='.flv']").each(function(){
		rel = $(this).attr("href");
		$(this).addClass("thickbox").attr({"rel":rel,"href":"#TB_inline?height=420&width=550&inlineId=flashPlayer"});
		$(this).click(function(){
		$('#showFlash').css('display', 'block').flash({ swf: '/uk/flash/Player.swf', height: 400, width:550, params: { wmode:'transparent'}, flashvars:{flv:rel}}); 
			return false;
		});
	});
	$("li.email a").each(function(){
		var rel = $(this).attr("href");
		
			$(this).click(function(){  var rel = $(this).attr('href');
    		$(this).attr('href', rel +  '?atUrl=' + loc);
		});
			});
	

			

		
	
	$('li.print a').click(function(){
		window.print();
		return false;
	});
	
	//add left border
	$("table.standard thead th:first").addClass("lb");
	
	//bios
	
	bioArray = $("div.col1 div.bio");
	var even = 1;
	for(i=0; i<bioArray.length; i++){
		if(i == 0){
			$(bioArray[0]).addClass("firstBio");
		}
		if(even == 1){
			$(bioArray[i]).addClass("nrm");
			even = 0;
		}else{
			even = 1;
		}
	}
	
	$("div#comments div.comment:odd").addClass("odd")	
	
	//Removes bottom-border from last item in secondary navigation
	$('div#secondary-nav li:last').addClass('last');
	
	$('div#secondary-nav ul').each(function(){
		if($(this).children("li").length == 0){
			$(this).remove();
		}
	});
	
	$('a.content-edit').parent("p").addClass("logged-in");
	$(".toggle").addClass("contracted").next('.toggle_content').hide();
			$(".toggle").click(function(){
				var $this = $(this);
				if( $this.is('.contracted')){$(this).removeClass("contracted").addClass("expanded");} else {$(this).removeClass("expanded").addClass("contracted");}
				$(this).nextAll('.toggle_content:eq(0)').toggle('fast');
				return false;
			});
			
			
	$("div#Enews2", $("#portlets")).each(function(){
		var $this = $(this);
		$this.replaceWith("<h2 class='eNews'>Subscribe to eNews</h2>	<div id='eNews'>		<p>Sign up to receive e-mail updates and news from Pitney Bowes Business Insight</p>		<p><a href='http://gw.vtrenz.net/?I9JT0TY6VK&amp;TB_iframe=true&amp;width=620&amp;height=400&amp;webSyncID=5e910925-8ade-b78c-053a-3c7570b85713' class='thickbox more' title='Subscribe to eNews'>Subscribe Now</a></p>	</div>"	);
		
	});
	
	
	
	

//Growl Popup
	
	
	
	jQuery.growl = function(title,message,image,priority) { 
  var create = function(rebuild) {
    
    var instance = document.getElementById('growlDock');
    if(!instance || rebuild) {
      instance = $(jQuery.growl.settings.dockTemplate).attr('id', 'growlDock').addClass('growl');
      
      if(jQuery.growl.settings.defaultStylesheet) {
        $('head').append('<link rel="stylesheet" type="text/css" href="' + jQuery.growl.settings.defaultStylesheet + '" />');
      }
      
    } else {
      instance = $(instance);
    }
    instance.css(jQuery.growl.settings.dockCss);
    
    $('body').append(instance);
    
    return instance;
  };
  
  var r = function(text, expr, val) {
    while(expr.test(text)) {
      text = text.replace(expr, val);
    }
    return text;
  };
  
  var notify = function(title,message,image,priority) {
    var instance = create();
    var html = jQuery.growl.settings.noticeTemplate;
    html = r(html, /%message%/, message);
    html = r(html, /%title%/, title);
    html = r(html, /%image%/, (image?image:jQuery.growl.settings.defaultImage));
    html = r(html, /%priority%/, priority);
    var notice = $(html);
    notice.css(jQuery.growl.settings.noticeCss);
    

    
    instance.append(notice);
    
    $('a[@rel="close"]', notice).click(function() {
    	 $.cookie('MIpro_clicked', '1', { expires: 1, path: '/', domain: 'pbinsight.eu', secure: false });
    	
		notice.remove();
	});
	$('a[@rel="muguk"]', notice).click(function() {
		var theHref = this;
		if (theHref.hostname && theHref.hostname !== location.hostname) {
			 $.cookie('MIpro_clicked', '1', { expires: 7, path: '/', domain: 'pbinsight.eu', secure: false });
			notice.remove();			
			$(theHref).bind('click keypress', function(event) {
				var code=event.charCode || event.keyCode;
				if (!code || (code && code == 13)) {
					if(pageTracker){
						var fixedLink = this.href;
						fixedLink = fixedLink.replace(/https?:\/\/(.*)/,"$1");
						fixedLink = '/outgoing/' + fixedLink;
						pageTracker._trackPageview(fixedLink);
					};
				};
			});
		};
	});
	

    setTimeout(function() {
      notice.fadeOut(jQuery.growl.settings.noticeFadeTimeout, function() {
        this.parentNode.removeChild(this);
      });
    }, jQuery.growl.settings.displayTimeout);
  };
  
  return notify(title,message,image,priority);
};

jQuery.growl.settings = {
  dockTemplate: '<div></div>',
  dockCss: {
    position: 'absolute',
    height:'300px',
    
    top: '160px',
    right: '150px',
    left:'50px',
    width: '300px'

  },
  noticeTemplate: 
    '<div class="notice" id="notice" style="min-height:125px; padding:10px; border 2px solid #ff0000">' +
   '<a id="noticeClose" title="Click here to close the popup" style="float:right" href="" rel="close" >close</a>'+
    ' <h3 style="margin-top: 15px;">Get More From Your Maps.</h3>' +
    ' <p>%message%</p>' +
    '</div>',
  noticeCss: {
    opacity: 1,
    backgroundColor: '#ffffff',
    border: '2px solid #97cb15',
    color: '#000000'}
    ,noticeRemove: function(notice, callback) {
		notice.animate({opacity: '0', height: '0px'}, {duration:jQuery.growl.settings.noticeFadeTimeout, complete: callback});
	},
	noticeFadeTimeout: 9000,
	displayTimeout: 3500,
	defaultImage: 'growl.jpg',
	defaultStylesheet: null,
	noticeElement: function(el) {
		$.growl.settings.noticeTemplate = $(el);
	}

};
	
	
	  $('.noticeTemplate').val($.growl.settings.noticeTemplate);
	$('#noticeClose').click(function() {	
		$.growl.create(true);
		 $.cookie('MIpro_clicked', '1', { expires: 1, path: '/', domain: 'pbinsight.eu', secure: false });
	

  });

    
  $('#updateNoticeTemplate').click(function() {
    $.growl.settings.noticeTemplate = $('.noticeTemplate').val();
    $.growl.create(true);
  });
  
  var msg = 'Please join us for the UK launch of MapInfo Professional v10.5 on 23 June.<br><br><a href="http://www.muguk.com" target="_blank" rel="muguk">For more information please click here &raquo;</a>';
  $('.noticeMessage').val(msg);
 

  var title = 'Hello World';
  $('.noticeTitle').val(title);
  
  $.growl.settings.displayTimeout = 16500;
//alert(loc);

if ($.cookie('MIpro_clicked') !== '1' && finger == '-1')  {	
 // $.growl(title, msg);
		}

});

