//***************************
//	Community Accounts Global Javascript Functions
//	Copyright 	Community Accounts, Gov of NL
//	Authors:	Kirill Beliakov and Jamie Dower
//***************************

var comInfoFetched = false; // added for handling RETURN key presses in geog selector

$(function(){
	// ++DIALOG MINIMIZE ADDON
	var _init = $.ui.dialog.prototype._init,
	minimizedDialogs = [];
		
	$.ui.dialog.prototype._init = function() {
		
		var self = this;
        _init.apply(this, arguments);

		uiDialogTitlebar = this.uiDialogTitlebar;
		this.resizeableHandle = this.uiDialog.find('.ui-resizable-se');

		this.uiDialog.bind('dialogclose',function(){
			self.cleanUp();
		});
		this.uiDialog.bind('dialogopen',function(e){
			self.checkMinimized(e);
		});		
		
	};
	
	$.extend($.ui.dialog.prototype, {
		isMinimized: false,
		restore: function() {
			this.uiDialog.show();

			this.uiDialog.resizable( "option", "disabled", false );
			this.resizeableHandle.show();
		 
			var ww = $(window).width()/2,
				wh = $(window).height()/2,
				x = ww - this.options.originalWidth/2,
				y = wh - this.options.originalHeight/2;
						
			this.element.show();
			this.uiDialog.find('.ui-dialog-buttonpane,.ui-resizable-handle').show();			
			this.uiDialog.animate({'left':x,'top':y,'width':this.options.originalWidth,'height':this.options.originalHeight}, 200);
			this._setOption('title',this.options.originalTitle);	
			this._setOption('draggable', this.options.originalDraggable);
		 
			this.cleanUp();
			this.isMinimized = false;
		},
		minimize: function() { 
			this.options.originalDraggable = this.options.draggable;
			this._setOption('draggable',false);
			this.uiDialog.resizable( "option", "disabled", true );
			this.resizeableHandle.hide();
		 
			this.options.originalWidth = this.uiDialog.width();
			this.options.originalHeight = this.uiDialog.height();
			this.options.originalTitle = this.uiDialog.find('.ui-dialog-title').html();
								
			this.uiDialog.animate({width:0, height:0, left:$('#footnoteIcon').offset().left, top:$('#footnoteIcon').offset().top}, 200,function(){$(this).hide();});

			this.element.hide();
			this.uiDialog.find('.ui-dialog-buttonpane,.ui-resizable-handle').hide();
			
			$('#footnoteIcon').effect("pulsate", { times:4 }, 2000);

			this.uiDialog.css('opacity',1.0);
			this._setOption('title',this.options.originalTitle.substring(0,15)+'...');
		 
			minimizedDialogs.push(this.uiDialog);
			this.isMinimized = true;
			this._isOpen = false;
		},
		cleanUp: function(){
			for(var i=0; i<minimizedDialogs.length; i++){
				if(minimizedDialogs[i]==this.uiDialog){
					minimizedDialogs.splice(i,1);
					var left = $(window).width();
					for(var j=0; j<minimizedDialogs.length; j++){
						minimizedDialogs[j].animate({'left':left-150*(j+1)},200);
					}
					break;
				}
			}
		},
		checkMinimized: function(e){
			if(this.isMinimized){
				this.restore(false);
			}
		}
	});	
	// --DIALOG MINIMIZE ADDON
	if ($.cookie('hidefootnotes') != 'true'){
		if($('#footnoteIcon').length > 0){
			$('#geographyInformation').dialog({ closeOnEscape: false,
								open: function(event, ui) { $(".ui-dialog-titlebar-close", $(this).parent()).hide(); },
								title:"Your Geography Information",width:500,height:300, 
								buttons: { "Hide": function() { $(this).dialog("minimize"); },"Auto-Hide by default": function() { $(this).dialog("minimize"); hideFootnotePanel(); }}});
			$('#footnoteIcon').click(function(){
				$('#geographyInformation').dialog("restore");
			});
		}
	}else{
		var footnoteShown = false;
		if($('#footnoteIcon').length > 0){
			$('#geographyInformation').dialog({ closeOnEscape: false,
								open: function(event, ui) { $(".ui-dialog-titlebar-close", $(this).parent()).hide(); },
								title:"Your Geography Information",width:500,height:300, 
								buttons: { "Hide": function() { $(this).dialog("minimize"); },"Auto-Hide by default": function() { $(this).dialog("minimize"); hideFootnotePanel(); }}});
			$('#geographyInformation').dialog("minimize");
			$('#footnoteIcon').click(function(){
				$('#geographyInformation').dialog("restore");
			});
		}
	}
	
	function hideFootnotePanel(){
		var $confirmDiv = '<div id="dialog-confirm"><p>Hide the footnote by default?  This can be reset by clearing cookies, and footnotes can still be read by clicking the asterisk (<span class="footnote">*</span>) in geography titles.</p></div>'
		$('BODY').prepend($confirmDiv);

		$( "#dialog-confirm" ).dialog({
					resizable: false,
					draggable: false,
					height:195,
					width:450,
					title:"Confirm auto-hide",
					modal: true,
					buttons: {
						"Yes": function() {
							$( this ).dialog( "close" );
							document.cookie = "hidefootnotes=true";
						},
						"No": function() {
							$( this ).dialog( "close" );
						}
					}
				});
	}
	// ++ COMBOBOX
	// used in the Geography Selector
	$.widget( "ui.combobox", {
			_create: function() {				
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						autoFocus: true,
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							comInfoFetched = false;
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text,
										value: text,
										option: this
									};
							}) );	
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
							$('#comInfoDiv').hide();
							fetchComInfo(ui.item.option.value);
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
								select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					}).click(function(){this.value='';}).keyup(function(e){
						if(e.which==13 && comInfoFetched){ // return key
							$('#proceedButton').click();
						}
					}).addClass( "ui-widget ui-widget-content ui-corner-left" );

				input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button type='button'>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Show All Items" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}
						
						// pass empty string as value to search for, displaying all results
						input.autocomplete("search", "");
						input.focus();
					});
					
					window.geogFocusField = input;
					window.focusInterval = setInterval("if(comInfoFetched){geogFocusField.focus();geogFocusField.select();geogFocusField=null;clearInterval(focusInterval);focusInterval=null;}",100);
			},

			destroy: function() {
				this.input.remove();
				this.button.remove();
				this.element.show();
				$.Widget.prototype.destroy.call( this );
			}
		});
	// -- COMBOBOX
		
	if($('#geographySelector').length>0){
		$('#geographySelector').dialog({title:'Geography Selector',modal:true,width:640,height:425,autoOpen:false,close:function(){removeGeogMenuFocus();$('ul.ui-autocomplete').hide();},open:function(){$(this).parent().find('div.ui-widget-header a,div.ui-widget-content').attr('tabindex',-1);}});
	}

	// ++ GEOGRAPHY DIALOG
	var n = $('#noncomdiv');
	if(n && n.length){
		n.dialog({width:500,modal:true,buttons: { "close": function() { $(this).dialog("close"); }}, closeOnEscape:true, draggable:true, autoOpen: false});
		$('#nonDialog').click(function(){
			$('#noncomdiv').dialog('open');
		});
	}
	// -- GEOGRAPHY DIALOG
	
	// ++ STYLE BUTTONS
	n = $('.btn');
	if(n && n.length){
		n.button();
	}
	// -- STYLE BUTTONS
	
	// ++ EXTERNAL LINKS
	n = $('a[rel="external"]');
	if(n && n.length){
		n.attr('target','blank');
	}
	// -- EXTERNAL LINKS
	
	// ++ SMARTMENUS
	$('input.checkMenuSearchStr').click(function(){
		this.value = '';
	}).keyup(function(e){
		if(e.which==13){ // "return" key
			changeParam(g_val_2, $('#menu_'+this.className.replace('checkMenuSearchStr ', '')+'_options option:selected').val());
		}else{
			var txt = this.value.toLowerCase(),
				txtlen = txt.length,
				select = $('select#menu_'+this.className.replace('checkMenuSearchStr ', '')+'_options'),
				opts = select.find('option');
			for(var i=1, size=opts.length; i<size; i++){
				if(opts[i].text.substring(0,txtlen).toLowerCase()==txt){
					select.attr('selectedIndex', i);
					return;
				}
			}		
		}
	});	
	// -- SMARTMENUS
	
	$('#changeContentPanelList li a').poshytip({
		className: 'tip-twitter',
		showTimeout: 0,
		hideTimeout: 0,
		alignTo: 'target',
		alignX: 'right',
		alignY: 'center',
		offsetX: 5,
		//xoffsetY: 0,
		allowTipHover: false,
		fade: false,
		slide: false
	});
	
	// main page only
	$('.contentselector').click(function(e){
		if (g_val_3 == ""){
			e.preventDefault();
			cur_rel = this.href;
			cur_rel = cur_rel.substring(0, cur_rel.indexOf('?'));
			cur_rel = cur_rel.indexOf('/')>-1 ? cur_rel.substring(cur_rel.lastIndexOf('/')+1, cur_rel.length) : cur_rel;
			fetchGeog('');
		}
	});

	// button or link
	$('#changeGeog').click(function(e){
		e.preventDefault();
		if (g_val_3 == ""){
			cur_rel = ($(this).attr('rel'));
		}
		fetchGeog('');
	});	
	
	$(window).unload(function(){loading(1);});
	
	$('#searchLink').click(function(e){
		e.preventDefault();
		var box = $('#searchBox'),
			$this = $(this),
			x = $this.parent().offset().left,
			y = $this.parent().parent().offset().top + $this.parent().parent().height();
		if(box.length==0){
			box = $('<div id="searchBox"><form action="/search.asp" method="get"><input type="text" name="s" id="s" /></form></div>').appendTo(document.body);
			box.find('form').submit(function(){
				loading(1);
			}).keypress(function(e){
				if(e.keyCode == 27){ // ESC key
					box.hide();
				}
			});
			box.find('input').click(function(e){
				$(this).val('');
			}).blur(function(){
				box.hide();
			});
		}
		
		var tmp = $(window).width() - (x + box.outerWidth(true));
		x = tmp < 0 ? x + tmp : x;
		
		box.css({'top':y,'left':x}).toggle(0, function(){
			if($(this).is(':visible')){
				$(this).find('input').focus();
			}
		});
	});
	
	$('#myca').fancybox({autoDimensions:false,width:640,height:480,type:'iframe'});
	
	$('.jbutton').button();
	$('a.jbutton').addClass('linkButton');
});

function validateSearchForm(){
	var f = document.myForm;
	if(f===undefined){
		f = document.getElementById("myForm");
	}
	if(f.s.value.length<3){
		alert('Search string is too short! It must be at least 3 characters long.');
		return false;
	}else{
		f.submit();
	}
}

// Email validation function
function isValidEmail(email){
	return /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test(email);
}

// Phone/fax number validation function
function isValidPhoneNumber(number,format){
	if (number=='' || format==''){
		return false;
	}
	var t = format.split('-');
	var pattern = '';
	for(var i=0; i<t.length; i++){
		pattern += '\\d{'+t[i].length+'}-';
	}
	if(pattern.length>0){
		pattern = '^' + pattern.substring(0,pattern.length-1) + '$';
		return (new RegExp(pattern)).test(number);
	}
	return false;
}

function loadURL(url){
	location.href = url;
}

/**
* Add/Change/Remove a single key=value pair from
* the query string and reload the page
* @param {String}    key The key name
* @param {String}    value The the value
* @param {Integer}   qStringOverwrite (Optional) 0 - change one key=value pair only (default), 1 - remove everything but the passed key=value pair
* @param {Integer}   immediateReload (Optional) 0 - do not reload page after the function call, 1 - reload page as soon as this function is called (default)
* @param {Function}  callback (Optional) Function to call after parameters were updated. Use if encryption is enabled.
*/
function changeParam(key,value,qStringOverwrite,immediateReload,callback){
	var url = location.href.split('?')[0];
	
	// When no arguments passed, reload the page with the most recent 'version' of query string
	if(arguments.length==0){
		loadURL(url + '?' + x1_4b8T);
		return;
	}
	
	qStringOverwrite = typeof qStringOverwrite=='undefined' ? 0 : qStringOverwrite;
	immediateReload = typeof immediateReload=='undefined' ? 1 : immediateReload;
	
	if(rdt4x18){ // do some server side magic using ajax, encryption is turned on
		var ok = function(data){
			if(typeof callback=='function'){
				callback(data);
			}else{
				x1_4b8T = data;
				immediateReload && loadURL(url+'?'+x1_4b8T);
			}
		}
		var fail = function(req, txtStatus, errorThrown){
			alert("changeParam() failed...");
		}
		var x1 = '', x2 = '';
		if($.isArray(key)){
			for(var i=key.length-1; i>=0; --i){
				x1 += 'x1='+key[i]+'&';
				x2 += 'x2='+(value[i]==null?'':value[i])+'&';
			}
			x1 = x1.substring(0,x1.length-1);
			x2 = x2.substring(0,x2.length-1);
		}else{
			x1 = 'x1='+key;
			x2 = 'x2='+(value==null ? '' : value);
		}
		var data = x1+'&'+x2+'&x3='+qStringOverwrite+'&x4='+encodeURIComponent(x1_4b8T);
		$.ajax({type:'POST', url:'/changeParam.asp', data:data, success:ok, error:fail});	
	
	}else{ // no need to bother the server, ecnryption is turned off
		if($.isArray(key)){
			var copy = x1_4b8T;
			for(var i=key.length-1; i>=0; --i){
				changeParam(key[i], value[i], 0, 0, null);
			}
			
			if(typeof callback=='function'){
				callback(x1_4b8T);
				x1_4b8T = copy;
			}else{
				immediateReload && loadURL(url+'?'+x1_4b8T);
			}			
		}else{
			key = unescape(key).toLowerCase();
			value = value==null ? null : unescape(value);
			var inQstring = new RegExp('\&?'+key+'=[^\&]*','g');
			if(qStringOverwrite==0){ // changing only one key=value pair, leaving the rest of the key=value pairs unchanged
				if(value==null){ //remove key=value pair from query string
					if(x1_4b8T==''){ // there's no query string at all - simply reload
						x1_4b8T = '';
						immediateReload && loadURL(url);		
					}else if(x1_4b8T.match(inQstring)){ // the key=value pair is in the query string - remove it
						var re = new RegExp(key+'=[^\&]*','g');
						x1_4b8T = x1_4b8T.replace(/#/,'').replace(re,'');
						immediateReload && loadURL(url+'?'+x1_4b8T);								
					}else{ // the key=value pair is NOT in the query string but there's a query string - reload
						x1_4b8T = x1_4b8T.replace(/#/,'');
						immediateReload && loadURL(url+'?'+x1_4b8T);	
					}	
				}else{ // update/create key=value pair
					if(x1_4b8T==''){ // there's no query string at all - create it
						x1_4b8T = key+'='+encodeURIComponent(value);
						immediateReload && loadURL(url+'?'+x1_4b8T);						
					}else if(x1_4b8T.match(inQstring)){ // the key=value pair is already in the query string - update it
						var re = new RegExp(key+'=[^\&]*','g');
						//Lowercase everything
						x1_4b8T=x1_4b8T.toLowerCase();
						x1_4b8T = x1_4b8T.replace(/#/,'').replace(re,key+'='+encodeURIComponent(value));
						immediateReload && loadURL(url+'?'+x1_4b8T);
					}else{ // the key=value pair is NOT in the query string but there's a query string - add it
						x1_4b8T = x1_4b8T.replace(/#/,'')+'&'+key+'='+encodeURIComponent(value);
						immediateReload && loadURL(url+'?'+x1_4b8T);
					}
				}
			}else{ // overwrite the query string, adding/changing only the passed in key=value pair
				x1_4b8T = key+'='+encodeURIComponent(value);
				immediateReload && loadURL(url+'?'+x1_4b8T);	
			}
			if(typeof callback=='function'){
				callback(x1_4b8T);
			}
		}
	}
}

var cur_rel;  
function fetchGeog(gt, opts){
	//loading(1);
	opts = opts ? opts : {};
	$('#geographySelector').empty().dialog('open');
	
	var k = [], v = [];
	k.push(g_val_2); v.push(g_val_3);
	k.push(g_vn_1); v.push(gt);
	k.push(g_vn_2); v.push(wt_val);
	if(opts.missingGeogcode){
		k.push(ctx_mg1); v.push(ctx_mg2);
	}
	
	changeParam(k, v, 0, 0, function(q){
		$.ajax({
			type: 'GET',
			url: '/geographyPage_ajax.asp',
			data: q,
			error:function(data){
				alert(data);
			}, 
			success: function(data){
				//loading(0);
				$('#geographySelector').fadeOut(100, function(){
					$(this).empty().html(data).fadeIn(100);
					if(gt==''){
						var ul = $(this).find('ul');
						$(document).keydown(geogMenuFocus);
						ul.focus();
						ul.find('a').hover(function(){$(this).focus();},function(){$(this).blur();});
						if(opts.qString){
							x1_4b8T = opts.qString
						}		
						return;
					}
					removeGeogMenuFocus();
					
					$('#proceedButton').click(function(e){
						e.preventDefault();
						if($(this).hasClass('disabled')){
							return false;
						}
						loading(1);

						if(opts.qString){
							x1_4b8T = opts.qString
						}		
	
						goToASP($('#selectBox').val());
					});
					fetchComInfo($('#selectBox').val());
					$('#aboutGeographyButton').click(function(e){
						e.preventDefault();
						if($(this).hasClass('disabled')){
							return;
						}
						$('#comInfoDiv').toggle(300);
					});		
					if(gt==gtv[0]){
						$("#selectBox").combobox();
					}else if(gt==gtv[1]){
						$('#nbhSearch').click(function(e){
							e.preventDefault();
							var v = $('#nbhsrch_inp').val();
							if(v.length<3){
								return;
							}
							$.ajax({
								type: 'GET',
								url: '/IncludeFiles/nbhsearchresults_v2.asp',
								data: 's='+encodeURIComponent(v),
								success: function(data){
									$('#nbhSearchDiv').html(data);
								}
							});
						}); 
										
						$('#comidSelectBox').change(function(e){
							e.preventDefault();
							$('#comInfoDiv').hide();
							$('#aboutGeographyButton').addClass('disabled');
							var v = $(this).val();
							if (v.length==0){
								return;
							}
							changeParam(g_val_2,v,0,0,function(q){
								$.ajax('/IncludeFiles/nbhsearchresults_v2.asp',{
									data: q,
									success: function(data){
										$('#nbhSelectDiv').html(data);
										if($('#selectBox').length>0){
											var v = $('#selectBox').val();
											if(v!=''){
												fetchGeog(v);
											}
											$('#selectBox').change(function(){
												$('#comInfoDiv').hide();
												fetchComInfo($('#selectBox').val());									
											});
										}
									}
								});
							});
						});
					}else if(gt==gtv[2]){
						$("#selectBox").combobox();
					}else{
						$('#selectBox').change(function(){
							$('#comInfoDiv').hide();
							fetchComInfo($('#selectBox').val());
						});					
					}
				});
			}
		});		
	});
}

function geogMenuFocus(e){
	var ul = $('#geogLevels');
	if(e.which==9){ // TAB
		if(ul.find('a:focus').length){
			return;
		}
		ul.find('li:eq(0) a').focus();
		return false;
	}else if(e.which==38){ // UP ARROW
		e.preventDefault();
		var i = ul.find('a:focus');
		i = i.length>0 ? i.parent().index() : -1;
		if(i==-1){
			ul.find('li:last a').focus();
		}else{
			if(i==0){
				ul.find('li:last a').focus();
			}else{
				ul.find('li:eq('+(i-1)+') a').focus();
			}
		}
		return false;
	}else if(e.which==40){ // DOWN ARROW
		e.preventDefault();
		var i = ul.find('a:focus');
		i = i.length>0 ? i.parent().index() : -1;
		if(i==-1){
			ul.find('li:first a').focus();
		}else{
			if(i==ul.find('li').length-1){
				ul.find('li:first a').focus();
			}else{
				ul.find('li:eq('+(i+1)+') a').focus();
			}
		}
		return false;
	}
	return true;
}

function removeGeogMenuFocus(){
	$(document).unbind('keydown', geogMenuFocus);
}

function canadaLink(param){
	goToASP(param);
}

function goToASP(param){
	if (cur_rel){		
		changeParam(g_val_2, param, 0, 0, function(d){loadURL(cur_rel+'?'+d);});
	}else{
		changeParam(g_val_2,param);
	}
}

function fetchComInfo(v){
	changeParam([g_val_2,g_vn_2], [v,wt_val], 0, 0, function(q){
		$.ajax('/IncludeFiles/geographyAbout.asp', {
			data: q+'&cur_rel='+cur_rel,
			success: function(data){
				$('#comstructureButton').addClass('disabled');
				if(data.length==0){
					$('#aboutGeographyButton').addClass('disabled');
					$('#comstructureButton').addClass('disabled');
				}else{
					$('#aboutGeographyButton').removeClass('disabled');
					$('#comInfoDiv').empty().html(data);
					var datafield = $('#data_available');
					var hasStructure = $('#has_structure');
					if(datafield && datafield.length && (datafield.val()=='2' || datafield.val()=='99' )){
						$('#proceedButton').addClass('disabled');
						if(datafield.val()=='2'){
							$('#comstructureButton').removeClass('disabled');
						}
						$('#comInfoDiv').show();
					}else{
						if(hasStructure && hasStructure.length && hasStructure.val()=='1'){
							$('#comstructureButton').removeClass('disabled');
						}
						$('#proceedButton').removeClass('disabled');
						$('#comInfoDiv').show();
					}				
					
					$('#comstructureButton').click(function(e){
						e.preventDefault();
						$('#comstructure').show(300);
					});		

					$('.offsetLink').click(function(e){e.preventDefault();goToASP($(this).attr('rel'));});				
				}
				comInfoFetched = true;
			},
			error: function(data){
				alert("Something went wrong.");
			}
		});
	});
}

function goPDF(){
	var v = $('#filename').val();
	if(v.length>0){
		location.href = v;
	}
}

function clearBox(o){
	o.value='';
}

function showGeogSelector(link){
	$.fancybox({'href':link,'type':'iframe','width':800,'height':640,'autoDimensions':false});
}

function loading(status){
	if(status){
		$.fancybox.showActivity();
	}else{
		$.fancybox.hideActivity();
	}
}	

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;
    }
};

