/*!
 * Zipboss Web API JavaScript Library v1.0.11
 * http://zipboss.com/zapi
 *
 * Copyright 2011, Kieran Guller
 * http://zipboss.com/zapi/license
 *
 *
 * Date: Wed May 4 17:17:48 2011 -0800
 */

 
(function($) {
	
	/*  Plugin Construction ///////////////////////////////////////////////////////////////
	 *
	 *	$.zapi()
	 *	$.fn.zapi()
	 *
	 */
	 
	// jQuery object - namespaces
	$.zapi = function( method ){ 
		
		if ( method == 'init' ) {
	      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
	    } else if ( typeof method === 'object' || ! method ) {
	      return methods.init.apply( this, arguments ); 
	    } else {
	      $.error( 'Method ' +  method + ' does not exist on jQuery.zapi' );
	    }   
	    return this; 
	}  
	
	// jQuery.fn object - namespaces  
	$.fn.zapi = function( method ){
    	
    	// force default init if no data
    	zdata = $.data(document.getElementsByTagName('head').item(0), 'zdata');
	    if (!zdata ) {
	    	// alert(' calling default init - no data!');
	      	methods.init.apply( this, arguments );
	    }
	   
    	if ( methods[method] ) {
    	  // call method
    	  
	      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
	    } else if ( typeof method === 'object' || ! method ) {
	      // call "pull" method if no method requested
	      return methods.get.apply( this, arguments );
	    } else {
	      // error
	      //alert('Method ' +  method + ' does not exist on jQuery.zapi');
	      $.error( 'Method ' +  method + ' does not exist on jQuery.zapi' );
	    }    
	  
	};

	/*  Plugin Methods ///////////////////////////////////////////////////////////////
	 *
	 *	init()
	 *	get()
	 *	destroy()
	 */
	var methods = {
     	init : function( options ) {
			
		   var host = location.host.replace('store.','').replace('test.','');
		   var domain = host.replace('.cloud.local.zipboss.com', ''); // strip out any dev domains
		   domain = domain.replace('.cloud.cloudt.zipboss.com', ''); // strip out any test domains
		   
		   // default settings
		   var settings = {
	      		'url'  		: 'https://www.zipboss.com/?c=api&m=web', // auto self domain minus "store."
	      		'room'  	: 'ZipBoss', 		/* 'iNet', 'ZipBoss' */
	      		'method'  	: 'ping', 		// default remote method
	      		'call'  	: '', 			// default remote function to call
	      		'domain' 	: domain, 		// auto self domain minus "store."
	       		'env' 		: 'production', // preview or production server
	       		'ssl' 		: 'true' 		// http/https
	       };

		   if ( options ) { 
	        	$.extend( settings, options );
	       }
		   
		   // get stored data	
	       zdata = $.data(document.getElementsByTagName('head').item(0), 'zdata');
		     
	       // if not previously initialized - set data
	       if ( ! zdata ) {
	       	   
	       	   // alert('no data yet, first instance');
	  		   $.data(document.getElementsByTagName('head').item(0), 'zdata', {
	               url : settings.url,
	               room : settings.room,
	               method : settings.method,
	               domain : settings.domain,
	               env : settings.env,
	               ssl  : settings.ssl
	           });
			   
			   // assign zdata
			   var method = 'getapp';
			   zdata = $.data(document.getElementsByTagName('head').item(0), 'zdata');
			   zdata.method = method;
			   
			   // getapp
			   $.ajax({
		            url: zdata.url,
		            dataType: "jsonp",
		            jsonp: 'callback',
	                crossDomain: true,
	                data: zdata,
                	success: function(data) {
                		// fire event
	                	handlers[method].apply( $(this), arguments );
			        },
		            error: function(data) {
		            	//alert('status: ' + status);
					}
		     	}); // end ajax
		     	
		     	// reset settings
		     	zdata.method = 'ping';
			}
			
			// initialize app
			//alert('new data: ' + zdata.method);
	        return this;
	     },
	     get : function( options, successfunc, errorfunc ) {

			// clone data and add options
			zdata = $.data(document.getElementsByTagName('head').item(0), 'zdata');
			var cdata = {};
			$.extend( cdata, zdata );
			
			if ( options ) { 
	        	$.extend( cdata, options );
	        }

	       	// variables
	       	var method = cdata.method;
			var callerarguments = Array.prototype.slice.apply(arguments);
			
			// get for each element
	       	return this.each(function() {
	     	
		       	// establish part to update
	     		var part = $(this);    
				
				// verify if form post
				if(method == 'set') {
					method = (part.is('form')) ? 'post' : method;
				}
							
				// check method for local cache
		        switch(method)
		        {
		        	case 'getstoredomain' :
		        		
		        		if(cdata.storedomain)
		        		{
		        			//alert('getstoredomain() called - local cache used');
		        			part.html(cdata.storedomain);
		        		}
		        		break;
		        	
		        	case 'post':
						
						jQuery.validator.addMethod("alpha", function(value, element, param) {
  							if(!param) return false;
  							return value.match(new RegExp("^[a-zA-Z]+$"));
						},"Only letters allowed");
						
						// form validation
				    	part.validate({
							onkeyup: false, 
							onfocusin: false,
							onblur: false,
							onfocusout: false,
							rules: {password: {required: true, minlength: 5},
									confirm_password: {required: true,equalTo: "#password"},
									zip:{maxlength: 9, minlength: 5, digits: true},
									firstName:{maxlength:50, alpha: true},
									lastName:{maxlength:50, alpha: true},
									email:{required:true, email:true}},
													   
							submitHandler: function(form) {
							
								//Define URL to PHP mail file
								var url = "/api/post/";
								
								//Define data string
				            	var datastring = $.param(cdata) + '&' + $(form).serialize();
								
								//Submit form
				            	$.ajax({
				                	type: "POST",
				                	url: url,
				                	data: datastring,
				                	success: function(data){
				                        // pass args
					                	var args = 
					                	Array.prototype.slice.apply(arguments).slice(0,1);
					                	args.push(successfunc);
					                	args.push(errorfunc);
					                	
					                	// fire event
					                	handlers['set'].apply( part, args );
						                    				                    
					                },
					                error: function(data)
									{
										// pass args
										var response =  {"message": data.responseText, 
												         "status": data.status};
										
										// args container
					                	var args = Array.prototype;
					                	args.push(response);
					                	
										// raise error
				            			if((errorfunc != undefined) && ($.isFunction(errorfunc)))
											errorfunc.apply( part, args );
				        			}
				         		});
				        	
				        	}
				    	
				    	}); // end ajax
				     	
				     	break;
				     		
					default:
						
		    			// call remote method
		        		$.ajax({
				            url: cdata.url,
				            dataType: "jsonp",
				            jsonp: 'callback',
			                crossDomain: true,
							data: cdata,
			                success: function(data) {

			                	// pass args
			                	var args = 
			                	Array.prototype.slice.apply(arguments).slice(0,1);
			                	args.push(successfunc);
			                	args.push(errorfunc);
			                	
			                	// fire event
			                	handlers[method].apply( part, args );
			                
			                },
		                	error: function(data) {
			                	// pass args
								var response =  {"message": data.responseText, 
										         "status": data.status};
								
								// args container
			                	var args = Array.prototype;
			                	args.push(response);
			                	
								// raise error
		            			if((errorfunc != undefined) && ($.isFunction(errorfunc)))
									errorfunc.apply( part, args );
				            	
				            }
				     	}); // end ajax
				}
	       		//alert('usedata - existing data: ' + data.appkey);
	       		
	       		return this;
	       	});
	       	
	     },
	     destroy : function( options ) {
			// Namespacing FTW
	        $.removeData(document.body, 'zdata');
	        return this;
	     }
    };
	
	/*  Plugin Event Handlers ///////////////////////////////////////////////////////////////
	 *
	 *	getapp()  			- called on init to gather app info
	 *	getstoredomain() 	- apply to span, a, p or div $(a).zapi({method:'getstoredomain'})
	 *	get() 				- apply to div $(div).zapi({method:'get',call:'functionname'});
	 *	set() 				- invoke an update $(div).zapi({method:'set',call:'functionname'});
	 *	getimage() 			- apply to image $(img).zapi({method:'getlogo'});
	 *	ping() 				- network call
	 *
	 */

	var handlers = {
     
       	getapp : function(data, success, error){
			
			// part (from context)
	     	var part = $(this);    
			
			// local data
			zdata = $.data(document.getElementsByTagName('head').item(0), 'zdata');
			    	
			// detect result
			var response = $.parseJSON(data);
			
			if(response.result=='true') {
				
				// wrap callback function
				var callbackfunc = function(response, part, success) {
					if((success != undefined) && ($.isFunction(success)))
						success.apply( this, arguments );
				};
				
				var properties = {
			      	'storedomain' : unescape(response.storedomain)	    
			    };
				   
				if ( properties ) { 
			        $.extend( zdata, properties );
			    }
			    
			    // callback
		    	callbackfunc(response, part, success);
				
			    // return
			    return true;
			}
			else {
		    	// set error message
				//part.html('<p>Check back soon!</p>');
		    	//alert(unescape(response.message));
		    	
		    	// wrap callback function
				var callbackfunc = function(response, part, error) {
					if((error != undefined) && ($.isFunction(error)))
						error.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, error);
				
		    	// return
		    	return false;
		    }
		   	
		},
		getstoredomain : function(data, success, error){
	
			// part to update (from context)
	     	var part = $(this);    
			
			// local data
			zdata = $.data(document.getElementsByTagName('head').item(0), 'zdata');
			    	
			// detect result
			var response = $.parseJSON(data);
			
			if(response.result=='true') {
				//part.html(response.html);
				//alert(unescape(response.message));
				
				// wrap callback function
				var callbackfunc = function(response, part, success) {
					if((success != undefined) && ($.isFunction(success)))
						success.apply( this, arguments );
				};
				
				var properties = {
			      	'storedomain' : unescape(response.storedomain)	    
			    };
				   
				if ( properties ) { 
			        $.extend( zdata, properties );
			    }
			    
			    // dump html
			    part.html(zdata.storedomain);
			    
			    // callback
		    	callbackfunc(response, part, success);
				
				// return
				return true;

			}
			else {
		    	// set error message
				
				// wrap callback function
				var callbackfunc = function(response, part, error) {
					if((error != undefined) && ($.isFunction(error)))
						error.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, error);

		    	// return
		    	return false;
		    }
		
		},
		getimage : function(data, success, error){
			
			// part to update (from context)
	     	var part = $(this);    
			
			// detect result
			var response = $.parseJSON(data);
			
			if(response.result=='true') {
				part.attr("src", unescape(response.url));
				//	alert(unescape(response.message));
				
				// wrap callback function
				var callbackfunc = function(response, part, success) {
					if((success != undefined) && ($.isFunction(success)))
						success.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, success);
				
			    // return
				return true;
			}
			else {
		    	// set error message
				
				// wrap callback function
				var callbackfunc = function(response, part, error) {
					if((error != undefined) && ($.isFunction(error)))
						error.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, error);

		    	// return
				return false;
		    }
		
		},
		get : function(data, success, error){
			
			// part to update (from context)
	     	var part = $(this);    
			
			// detect result
			var response = $.parseJSON(data);
			//alert(response.method);
			if(response.result=='true') {
				
				// wrap callback function
				var callbackfunc = function(response, part, success) {
					if((success != undefined) && ($.isFunction(success)))
						success.apply( this, arguments );
				};
				
				var insert = response.insert;
				part.hide();
				if(insert=='replace') {part.html(unescape(response.html));}
				else if(insert=='prepend') {part.prepend(unescape(response.html));}
				else if(insert=='head-links') {
						
					for (var url in response.urls)
  					{
	  					var link = unescape(response.urls[url]);
						var headID = document.getElementsByTagName("head")[0];         
						var cssNode = document.createElement('link');
						cssNode.type = 'text/css';
						cssNode.rel = 'stylesheet';
						cssNode.href = link;
						cssNode.media = 'screen';
						headID.appendChild(cssNode);
					}

				}
				else {part.append(unescape(response.html));}
				
				// animate	
				if(response.animation=='slideDown') {part.slideDown(700, callbackfunc(response, part, success));}
				else if(response.animation=='slideRight') {part.animate({ width: 'show' }, callbackfunc(response, part, success));}
				else if(response.animation=='fadeIn') {part.fadeIn(700, callbackfunc(response, part, success));}
				else if(response.animation=='slideUp') {part.slideUp('fast',callbackfunc(response, part, success));}
				else if(response.animation=='hide') {part.hide(0,callbackfunc(response, part, success));}
				else {part.show(0,callbackfunc(response, part, success));}
				//alert(unescape(response.message));
				
				// return
				return true;
			}
			else {
		    	// set error message
				//part.html('<p>' + unescape(response.message) + '</p>');
		    	
		    	// wrap callback function
				var callbackfunc = function(response, part, error) {
					if((error != undefined) && ($.isFunction(error)))
						error.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, error);
	
		    	// return
		    	return true;
		    }
		
		},
		set : function(data, success, error){
					
			// part to update (from context)
	     	var part = $(this);    
			
			// detect result
			var response = $.parseJSON(data);
			
			if(response.result=='true') {
			
				// wrap callback function
				var callbackfunc = function(response, part, success) {
					if((success != undefined) && ($.isFunction(success)))
						success.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, success);
					
			    // return
				return true;
	
			}
			else {
		    	
		    	// wrap callback function
				var callbackfunc = function(response, part, error) {
					if((error != undefined) && ($.isFunction(error)))
						error.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, error);
					
				// return
				return false;
		    }
		    
		},
		ping : function(data, success, error){
							
			// part to update (from context)
	     	var part = $(this);    
			
			// detect result
			var response = $.parseJSON(data);
			
			if(response.result=='true') {
				//alert(response.message);
				
				// wrap callback function
				var callbackfunc = function(response, part, success) {
					if((success != undefined) && ($.isFunction(success)))
						success.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, success);
						
			    // return
				return true;

			}
			else {
		    	// set error message
				//alert(unescape(response.message));
				
				// wrap callback function
				var callbackfunc = function(response, part, error) {
					if((error != undefined) && ($.isFunction(error)))
						error.apply( this, arguments );
				};
				
				// callback
		    	callbackfunc(response, part, error);
				
				// return
				return false;
		    }
		}
	}
	
	
}(jQuery));




// library functions -----------------------------------------------------------

function zapi_ucwords (str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/ucwords
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // +      input by: James (http://www.james-bell.co.uk/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: ucwords('kevin van  zonneveld');
    // *     returns 1: 'Kevin Van  Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

function zapi_str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = r instanceof Array,
        sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}


/*!
 * Zipboss Loom JavaScript Library v1.0.0
 * http://zipboss.com/loom
 *
 * Copyright 2011, Kieran Guller
 * http://zipboss.com/loom/license
 *
 *
 * Date: San Jul 9 20:20:18 2011 -0800
 */


(function($) {
	
	/*  Plugin Construction ///////////////////////////////////////////////////////////////
	 *
	 *	$.loom()
	 *	$.fn.loomdata()
	 *
	 */
	 
	// jQuery object - namespaces
	$.loomdata = function( params ){
	
		if(!params){
			return $(document.body).data('data-loom');
    	}
	
		$(document.body).data('data-loom', params);
	};
    
    $.loom = function( method ){ 
		
		if ( method == 'init' ) {
	      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
	    } else if ( typeof method === 'object' || ! method ) {
	      return methods.init.apply( this, arguments ); 
	    } else {
	      $.error( 'Method ' +  method + ' does not exist on jQuery.loom' );
	    }   
	    return this; 
	}  
	
    // jQuery.fn object - namespaces  
	$.fn.loomdata = function( params ){
		if(!params){
			return $(this).data('data-loom');
    	}
    	
		$(this).data('data-loom', params);
    };
	
}(jQuery));
