/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) {return s;} : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
;(function($){
    $(window).load(function(){
        window.loaded=1;
    });
    $.windowLoaded=function(fn){
        var windowLoadedFn=window.loaded?(function(fn){fn.call(window);}):(function(fn){$(window).load(fn);});
        windowLoadedFn(fn);
    };
	$(function(){
		$.gravy={};
		$.gravy.debug=function(str){
			if(console){
				if(console.log){
					console.log(str);
				}
			}
		};
		$.gravy.common={
			objToUrl:function($obj,$addQ,$escape){
				$addQ=($addQ==undefined)?false:$addQ;
				$escape=($escape==undefined)?false:$escape;
				var result=($addQ)?"?":"";
				var c=0;
				for(var item in $obj){
					result+=(c==0)?"":"&";
					if($.isArray($obj[item])){
						for(var d=0;d<$obj[item].length;d++){
							result+=(d==0)?"":"&";
							result+=item+"[]="+(($escape)?escape($obj[item][d]):$obj[item][d]);
						}
					}else{
						result+=item+"="+(($escape)?escape($obj[item]):$obj[item]);
					}
					c++;
				}
				return(result);
			},
			urlToObj:function($url){
				var result={};
				var ar1=$url.split(/&/);
				var ar2,tmp;
				for(var c=0;c<ar1.length;c++){
					ar2=ar1[c].split(/=/);
					if(ar2.length==1){
						ar2.push("");
					}
					ar2[1]=decodeURIComponent(ar2[1].replace(/\+/gi," "));
					if($.isArray(result[ar2[0]])){
						result[ar2[0]].push(ar2[1]);
					}else if(result[ar2[0]]){
						tmp=ar2[1];
						result[ar2[0]]=[];
						result[ar2[0]].push(tmp);
						result[ar2[0]].push(ar2[1]);
					}else{
						result[ar2[0]]=ar2[1];
					}
				}
				return(result);
			},
			bookmark:function($title,$url){
				if(window.sidebar){
					// Mozilla Firefox Bookmark
					window.sidebar.addPanel($title,$url,"");
				}else if(window.external){
					// IE Favorite
					window.external.AddFavorite($url,$title);
				}else if(window.opera){ // Opera 7+
					return(false);
				}else{
					// for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
					alert('Unfortunately, this browser does not support the requested action, please bookmark this page manually.');
				}

			}
		};
		$.gravy.common.ajax={
			form:function($otps){
				var form=$($otps.form);
				if(form.length>0){
					var serialised=form.serialize();
					serialised=$.gravy.common.urlToObj(serialised);
					var opts={output:"json"};
					$.extend(opts,serialised);
					$.extend(opts,$otps.data);
					$.ajax({
						url:form.attr("action"),
						data:opts,
						dataType:"json",
						success:function(data,status,xhr){
							if($otps.success){
								$otps.success(data);
							}
						},
						error:function(xhr,status,error){
							if($otps.error){
								$otps.error(error);
							}
						}
					});
				}else if($otps.error){
					$otps.error("The form element was not found.");
				}
			}
		};
		$.gravy.validator={
			isEmail:function($val){
				return(/^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,8}$/gi.test($val));
			}
		};
		$.gravy.track={};
		$.gravy.track.ga={
			event:function($onsite,$element,$value){
				$onsite=($onsite==true)?"Onsite":"Outbound";
				_gaq.push(['_trackEvent',$onsite,$element,$value]);
			}
		};
		$.gravy.modal={
			is:false,
			show:function($opts){
				var opts={
					url:"/b/about-us",
					width:570,
					maxHeight:500,
					modal:true,
					resizable:false,
					position:['center','center'],
					closeOnEscape:true,
					close:function(evt,ui){
						$.gravy.modal.is=false;
					}
				};
				$.extend(opts,$opts);
				$.gravy.modal.is=true;
				$.gravy.modal.loading({show:false});
				var diag=$('#blank-jax');
				var content=$('#jax-content');
				var closer=$("<a></a>").attr("href","#close").attr("title","close").addClass("jaxClose").click(function(){
					$('.diag').dialog('close');
					return(false);
				});
				$.gravy.modal.error();
				if(opts.selector){
					diag=$(opts.selector);
					if(opts.html){
						diag.html(opts.html);
					}
					diag.dialog(opts);
					diag.parent().prepend(closer);
					if(opts.onLoad){
						opts.onLoad();
					}
				}else if(opts.html){
					diag.html(opts.html);
					diag.dialog(opts);
					if(opts.onLoad){
						opts.onLoad();
					}
				}else if(opts.url){
					content.load(
						opts.url,
						{},
						function(responseText,textStatus,XMLHttpRequest){
							if(opts.script){
								var scpt=(opts.url.substr(-1)=="/")?opts.url:opts.url+"/";
								$.getScript(scpt+"script",function(data,textStatus){
									diag.dialog(opts);
									diag.parent().prepend(closer);
									if(opts.error){
										$.gravy.modal.error(opts.error);
									}
									if(opts.onLoad){
										opts.onLoad();
									}
								});
							}else{
								diag.dialog(opts);
								diag.parent().prepend(closer);
								if(opts.error){
									$.gravy.modal.error(opts.error);
								}
								if(opts.onLoad){
									opts.onLoad();
								}
							}
						}
					);
				}
			},
			loading:function($opts){
				var opts={
					 show:true,
					 text:"Please wait: loading..."
				};
				$.extend(opts,$opts);
				$("#jax-content").toggle(!opts.show);
				$("#jax-loader").toggle(opts.show);
				$("#jax-loader SPAN").html(opts.text);
			},
			error:function($text){
				if($text==undefined||$text.length<1){
					$('.diag .error').html("").hide();
				}else{
					$('.diag .error').html($text).show();
				}
			},
			hide:function(){
				$('.diag').dialog('close');
				$.gravy.modal.is=false;
			}
		};
	});
})(jQuery);

