//

var img=new Image
img.src="/common/images/icons/btn_processing.gif"

Sonix.pop=function(url,w,h){
	window.open(url,'pop','width='+w+', height='+h);
};

Sonix.call=function(controller, action, qs, callback){
	
	if(callback){var callbackAction=function(){ callback() }}else{ var callbackAction=function(){} }

	url = Sonix.controller.getUrl(controller, action, qs);
	$.get(url, function(){ callbackAction(); } ); 

}

Sonix.fx={};
Sonix.price={};
Sonix.controller={
	getUrl:	function($controller,$action,$qs){
		return Sonix.rootpath+'controllers/'+$controller+'/?action='+$action+'&'+$qs
	}
};
Sonix.refresh=function(){
	setTimeout('window.location=window.location+" "');
	}

Sonix.session={
	log:	function(logtype,detail){
		
		if(detail=='undefined' || detail==null){detail=''}
		$.get(Sonix.controller.getUrl('session','sessionlog','test=-1&t='+logtype+'&d='+detail))
		}
	}
//Template 


Sonix.dialog=function(selector,settings){
		//options
		var options={width:350,
			height:350,
		autoopen:true, 
			resizable:false,
			bgiframe:true,
			movable:false,
		closable:true, 
			overlay:{'opacity':0.5, 'background-color':'#000'}
		}

		
		//Extend
		$.extend(options, settings)
		
		$('body').addClass('jui'); 

		//Puts options
		var dialog = $(selector).addClass('dialogholder').addClass('flora').show().dialog(options)
			
				if(!options.closable){
				$('.ui-dialog-titlebar-close').hide()
				}else{
				$('.ui-dialog-titlebar-close').show(); 
			}
		return dialog;



}


Sonix.popDialog=function(url, x, y, settings ){

	//Destoy dialog
	$('#prompt_popup').remove();

	if($('#prompt_popup').size()==0){
		$('body').append($('<div id="prompt_popup" style="display:none"><iframe id=sonix_popup_frame style="width:100%; height:100%"></iframe></div>'))
	}else{
		//reset for now
		$('#sonix_popup_frame').attr('src','about:blank');
	}

	var options={title:'&nbsp;',buttons:{}, width:x, height:y, closable:true, modal:true}
	$.extend(options, settings); 
	$('#sonix_popup_frame').attr('src',url);
	return Sonix.dialog('#prompt_popup', options)

}



Sonix.loadingDialog=function(text){
	if(!text){text=' '}
	var options={buttons:{},icon:'loading', width:150, height:100, closable:false, modal:true}
		

		if($('#prompt_loading').size()==0){
		$('body').append($('<div id="prompt_loading" style="display:none"><div style="float:left; width:55px"><img id="confirm_icon" src="/common/images/icons/btn_processing.gif"/></div></div>'))
	}

Sonix.dialog('#prompt_loading', options)
	$('.ui-dialog-titlebar-close').hide()
}

Sonix.confirm=function(question, callback, cancelcallback, settings){


	var options={
			modal:true,
			icon: false,
			buttons: {
						'Ok':function(){callback(); $(this).dialog("close");},
						'Cancel':function(){$(this).dialog("close");  cancelcallback();  }
					}, height:150, title:'&nbsp;'
			}
	
	$('#prompt_confirm').remove(); 

	if($('#prompt_confirm').size()==0){
		$('body').append($('<div id="prompt_confirm" style="display:none"><div style="float:left; width:75px"><img id="confirm_icon" /></div><div id="confirm_question" style="font-size:14px; font-weigth:bold;  "></div></div>'))
	}

	$.extend(options, settings)
	
	if(options.icon){
		//Check for presets
		switch(options.icon){
		    case 'loading':icon='/common/images/icons/btn_processing.gif';  break; 
			case 'warning':icon='/common/images/icons/exclamation.png';  break; 
			case 'question':icon='/common/images/icons/option_Help.gif'; 	
		}

		$('#confirm_icon').attr('src',icon).show();
	}else{
		$('#confirm_icon').hide();
	}
	$('#confirm_question').html(question);
	
	Sonix.dialog('#prompt_confirm', options);

}

Sonix.fx.applyTemplate=function(selector,template,data,options){
			
				var defaults={
							//Start and end settings
							start:0,
							end:data.length,
							data:false,
							//Paging system
							pagesize:false,
							callback:function(){alert('ss')},
							page:false,
							dataContainer:false
					
					}
			//Set defaults
			this.options=$.extend(defaults,options||{});
			this.options.data=data;
			//Set start and end when pading is enabled
			if(this.options.pagesize){
				if(!this.options.page){this.options.page=0}
				
				with(this.options){
					start=page*pagesize; 
					end=(data.length<start+pagesize)?data.length:start+pagesize;
					
					if(start>end){return;}
				}
			}

		
			var t=$.template(template);
			$(selector).empty(); 
			
			
			//Empty
			if(data.length==0 && options.tplempty){
				$(selector).append(tplempty);
				return; 
				}
			//Apply			
			
			for(i=this.options.start;i<this.options.end;i++){
					var html=t.apply(data[i])
					$(html).appendTo(selector).data("tplData",data[i]).addClass('tplItem')
				}
				
				this.options.callback.call();
		}

//Set a div with a warning message
Sonix.fx.emptyBox=function(selector,message){
		
		$(selector).hide().empty().html('<div class="sonix-warning">'+message+'</div>').fadeIn();
	
	}
//Set a div with a warning message
Sonix.fx.loadingBox=function(selector,message){
		if(!message){message=""}
		$(selector).hide().empty().html('<div class="sonix-loading">'+message+'</div>').fadeIn();
	
	}
	
Sonix.fx.message=function(content, options){
	if(!!Sonix.fx.alertCache){
		Sonix.fx.alertCache.empty().html('<span class="closeMessages"><a href="#" style="display:none;">click to dismiss</a></span>'+content);
	}else{
		Sonix.fx.alertCache=$('<div class="alert"><span class="closeMessages"><a href="#" style="display:none;">click to dismiss</a></span>'+
							  content+'</div>').appendTo(document.body);
	}
	$('a', Sonix.fx.alertCache).click(function(){
		Sonix.fx.alertCache.stop();
		Sonix.fx.alertCache.fadeOut('slow');
		return false;
	});

	var leftMargin=($(document.body).width()-Sonix.fx.alertCache.width())/2;
	Sonix.fx.alertCache.css({top:50, left:leftMargin, display:'block'});
	Sonix.fx.alertCache.animate({top:30, opacity:1.0}, 1000);
	Sonix.fx.alertCache.fadeOut();
}

Sonix.fx.warning=function(content,options){
	if(!!Sonix.fx.errorCache){
		Sonix.fx.errorCache.empty().html('<span class="closeMessages"><a href="#" style="display:none;">click to dismiss</a></span>'+content);
	}else{
		Sonix.fx.errorCache=$('<div class="alert-error"><span class="closeMessages"><a href="#" style="display:none;">click to dismiss</a></span>'+
							  content+'</div>').appendTo(document.body);
	}
	$('a', Sonix.fx.errorCache).click(function(){
		Sonix.fx.errorCache.stop();
		Sonix.fx.errorCache.fadeOut('slow');
		return false;
	});

	var leftMargin=($(document.body).width()-Sonix.fx.errorCache.width())/2;
	Sonix.fx.errorCache.css({top:50, left:leftMargin, display:'block'});
	Sonix.fx.errorCache.animate({top:30, opacity:1.0}, 1000);
	Sonix.fx.errorCache.fadeOut();
}
 
//Standard ajax answer 
Sonix.fx.ajaxAnswer=function(data){
	
	//Transform in json
	eval('data='+data);
	
	//Redir
	if(data.redir){Sonix.fx.go(data.redir);}
	
	//Message
	if(data.message){
	
			if( $('#messagebox').size() ){$('#messagebox').show().html(data.message); }else{
				if(data.success){Sonix.fx.message(data.message)}else{Sonix.fx.warning(data.message)};
									}
		}
	//Eval
	try{eval(data.callback)}catch(e){};	
	
	}
//Simple redirector
Sonix.fx.goView=function(x,qs){if(!qs){qs=''}; window.location=Sonix.path+'?view='+x+'&'+qs}
//Simple redirector
Sonix.fx.go=function(x){window.location=x}



Sonix.uploadform=function(it){  
					
					
				 //Get unique id
					var uid=String(+new Date()).substring(1,8);
				   
				   	
				   //Prepare post url
					var frmaction=Sonix.controller.getUrl('cart','uploadfiles','uploadid='+uid);
				   
				   //set action
					it.action=frmaction;
									
					//Status bar container
					var statusbar='#statusbar'; 
					 
					 $('#uploadsubmit').hide(); 
					setTimeout('Sonix.uploadStatus("'+statusbar+'", '+uid+')',1000)
					//alert(this.action)
					return true; 	
					
				
		   		} 
  
Sonix.uploadStatus=function(statusbar, uid){
	
	//Get status  
	var url=Sonix.controller.getUrl('uploadstatus','get','uploadid='+uid);
	
	$.getJSON(url, function(a){    
					 
					var html="<div class=loadingStatus>"
					html+=Math.round(a.bytesDone/1068)+"kb /" + Math.round(a.bytesTotal/1068)
					html+="  &nbsp;"+a.secondsLeft+" sec. remaining";
					var width=Math.round(a.bytesDone/a.bytesTotal*200)
					html+="<div class=loadingStatusbar><div class=loadingStatusbarInner style=\"width:"+ width+"px\"></div></div>"
					
					html+="</div>"
					
					$('#statusbar').html(html)
										
					
					
					})
				
						
						setTimeout('Sonix.uploadStatus("'+statusbar+'", '+uid+')',1000)
	
	
	}
	
	
var ChatFx = {
    
	run: function(js){
		if(window.opener) setTimeout('window.opener.'+js,0);
	},
    go: function(url){
		if(url.indexOf('://')===-1){
			if(chatclientglobal.info){
				url="http://www."+chatclientglobal.info.domain+url;
			}else{
				url="http://www.wowimpression.com"+url;
			}
		}
		url=String(url).replace(/&amp;/g,'&');
		if(opener) opener.location=url; 
		setTimeout('window.focus()',2000);
    },
    go2: function(){
		var url=arguments[0];
		if(url.indexOf('://')===-1){
			if(chatclientglobal.info){
				url="http://www."+chatclientglobal.info.domain+url;
			}else{
				url=url.replace('&amp;','&');
				url="http://www.wowimpression.com"+url;
			}
		}
		for(var i=1, l=arguments.length; i<l; i++){
			url+=String(arguments[i]).replace(/&amp;/g,'&');
		}
		
		
		if(opener) opener.location=url; 
		setTimeout('window.focus()',2000);
    },
    clearMsgbox: function(){
        if(chatclientglobal.chatsession){
            chatclientglobal.chatsession.clearMessageBox();
        }
    },
    hello: function(name,msg,display){
        if(display){
            alert('Hello, '+name+', '+msg);
        }else{
            alert('Hello, '+name+' !');
        }
    },
    testObject: function(options){
        $j.each(options,function(key,val){
            $j('body').append(new Element('div').update(key+'='+val));
        });
    },
	shakeScreen: function(){
		var n=3;
		window.focus();
		if(window.moveBy){
			for(var i=10; i>0; i--){
				for(var j=n; j>0; j--){
					window.moveBy(0,i);
					window.moveBy(i,0);
					window.moveBy(0,-i);
					window.moveBy(-i,0);
				 }
			  }
		}else{alert('No Parent');}
	}
};



try{
	
	if(window.logableset !== true){
		$('.clicklog').livequery('click',function(){
		
			Sonix.session.log($(this).attr('id')+'.click')
		
		})
		
		window.logableset=true; 
	}
	
	}catch(e){}

// This jQuery v1.1.3 plugin will return an delimited
		// list of the given attribute of all elements in the
		// current jQuery stack.
 
		jQuery.fn.attrList = function( strAttribute, strDelimiter ){
			// Start out with an empty value list. This list
			// will eventually contain a delimited list of
			// each attribute value.
			var strValueList = "";
 
			// Check to see if we were given a delimiter.
			// By default, we will use the comma.
			strDelimiter = (strDelimiter ? strDelimiter : ",");
 
			// Loop over each element in the jQuery stack and
			// add the given attribute value to the list.
			this.each(
				function( intI ){
					// Get a jQuery version of the current
					// stack element.
					var jNode = $( this );
 
					// Add the attribute to the list. When
					// adding the value, check to see if
					// we need to add the leading delimiter.
					strValueList += (
						(strValueList.length ? strDelimiter : "") +
						jNode.attr( strAttribute )
						);
 
				}
				);
 
			// Return the value list.
			return( strValueList );
		};

(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );



function Sonix_Template(settings){

	// Default Settings
	var defaults = { 'loadingdiv':'#tpl_loading',
					'container':'#tpl_container',
					'url' : '/mysite3/controllers/formtemplate/', //default for the form system
					'pager':'#tpl_pagination', callback : function(){},
					 ps:9}

	//
	this.currentPage = false; 

	//Extend
	this.options = $.extend(defaults, settings);
	this.customdata = {};
	//Set a self reference
	var $self=this; 

	//Custom data function
	this.setData =	function(data){ $.extend( $self.customdata, data) },

	//Feature	
	this.getPage = function(p){

							

							//leave if alreayde there
							if ($self.currentPage == p){return;}
						
							//Reset
							if(p == -1){p = 0}
						
							//Set Loading
							$($self.options.container).html("<div class='sonix-loading'></div>");
							$($self.options.container).css('opacity', 0.2)
							$($self.options.loadingdiv).show(); 
							//Prepare Data
							data={ pn : p, ps : $self.options.ps}
							$.extend(data, $self.customdata)
							//Send
							
							$.getJSON($self.options.url , data, function(a){
							if(a.html == ''){a.html = "<div class='sonix-warning'>No data</div>"}
									//Set HTML
									$($self.options.container).html(a.html);
									$($self.options.container).css('opacity', 1)
									$($self.options.loadingdiv).show(); 
									//Event callback
									$self.options.callback(); 
									//Prepare pagination
										var total = a.count
										var pn = a.pn
										var ps = a.ps
										$self.currentPage=pn
										$($self.options.pager).pagination(total,
												{
												current_page:pn,
												items_per_page:ps,
												num_display_entries: 4,
												callback: function(p){$self.getPage(p)}
												})
								})
					
				}//end Getpage



}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


	String.prototype.Left=function(n){
	if (n <= 0)
	    return "";
	else if (n > String(this).length)
	    return str;
	else
	    return String(this).substring(0,n);
}
String.prototype.Right=function(n){
    if (n <= 0)
       return "";
    else if (n > String(this).length)
       return str;
    else {
       var iLen = String(this).length;
       return String(this).substring(iLen, iLen - n);
    }
}
