;
(function($) {
	/*
	**	Just an equivalent of the corresponding libc function
	**
	**	var str=jQuery.sprintf("%010d %-10s",intvalue,strvalue);
	**
	*/

	$.sprintf=function(fmt)
	{
		return _sprintf_(fmt,arguments,1);
	}
	/*
	**	vsprintf takes an argument list instead of a list of arguments (duh!)
	**	(useful when forwarding parameters from one of your functions to a printf call)
	**
	**	str=jQuery.vsprintf(parameters[,offset]);
	**
	**		The 'offset' value, when present, instructs vprintf to start at the
	**		corresponding index in the parameter list instead, of 0
	**
	**	Example 1:
	**
	**		function myprintf(<printf like arguments>)
	**		{
	**			var str=jQuery.vsprintf(arguments);
	**			..
	**		}
	**		myprintf("illegal value : %s",somevalue);
	**
	**
	**	Example 2:
	**
	**		function logit(level,<the rest is printf like arguments>)
	**		{
	**			var str=jQuery.vsprintf(arguments,1);	// Skip prm #1
	**			..
	**		}
	**		logit("error","illegal value : %s",somevalue);
	**
	*/

	$.vsprintf=function(args,offset)
	{
		if(offset === undefined)
		{
			offset=0;
		}
		return _sprintf_(args[offset],args,offset+1);
	}
	/*
	**	logging using formatted messages
	**	================================
	**
	**	If you _hate_ debugging with alert() as much as I do, you might find the
	**	following routines valuable.
	**
	**	jQuery.alertf("The variable 'str' contains: '%s'",str);
	**		Show an alert message with a printf-like argument.
	**
	**	jQuery.logf("This is a log message, time is: %d",(new Date()).getTime());
	**		Log the message on the console with the info level
	**
	**	jQuery.errorf("The given value (%d) is erroneous",avalue);
	**		Log the message on the console with the error level
	**
	*/
	$.alertf=function()
	{
		return alert($.vsprintf(arguments));
	}

	$.vlogf=function(args)
	{
		if("console" in window)
		{
			console.info($.vsprintf(args));
		}
	}

	$.verrorf=function(args)
	{
		if("console" in window)
		{
			console.error($.vsprintf(args));
		}
	}

	$.errorf=function()
	{
		$.verrorf(arguments);
	}

	$.logf=function()
	{
		$.vlogf(arguments);
	}


	/*-------------------------------------------------------------------------------------------
	**
	**	Following code is private; don't use it directly !
	**
	**-----------------------------------------------------------------------------------------*/

	FREGEXP	= /^([^%]*)%([-+])?(0)?(\d+)?(\.(\d+))?([doxXcsf])(.*)$/;
	HDIGITS	= ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];

	function _empty(str)
	{
		if(str===undefined || str===null)
		{
			return true;
		}
		return (str == "") ? true : false;
	}

	function _int_(val)
	{
		return Math.floor(val);
	}

	function _printf_num_(val,base,pad,sign,width)
	{
		val=parseInt(val,10);
		if(isNaN(val))
		{
			return "NaN";
		}
		aval=(val<0)?-val:val;
		var ret="";

		if(aval==0)
		{
			ret="0";
		}
		else
		{
			while(aval>0)
			{
				ret=HDIGITS[aval%base]+ret;
				aval=_int_(aval/base);
			}
		}
		if(val<0)
		{
			ret="-"+ret;
		}
		if(sign=="-")
		{
			pad=" ";
		}
		return _printf_str_(ret,pad,sign,width,-1);
	}

	function _printf_float_(val,base,pad,sign,prec)
	{
		if(prec==undefined)
		{
			if(parseInt(val) != val)
			{
				// No decimal part and no precision -> use int formatting
				return ""+val;
			}
			prec=5;
		}

		var p10=Math.pow(10,prec);
		var ival=""+Math.round(val*p10);
		var ilen=ival.length-prec;
		if(ilen==0)
		{
			return "0."+ival.substr(ilen,prec);
		}
		return ival.substr(0,ilen)+"."+ival.substr(ilen,prec);
	}

	function _printf_str_(val,pad,sign,width,prec)
	{
		var npad;

		if(val === undefined)
		{
			return "(undefined)";
		}
		if(val === null)
		{
			return "(null)";
		}
		if((npad=width-val.length)>0)
		{
			if(sign=="-")
			{
				while(npad>0)
				{
					val+=pad;
					npad--;
				}
			}
			else
			{
				while(npad>0)
				{
					val=pad+val;
					npad--;
				}
			}
		}
		if(prec>0)
		{
			return val.substr(0,prec);
		}
		return val;
	}

	function _sprintf_(fmt,av,index)
	{
		var output="";
		var i,m,line,match;

		line=fmt.split("\n");
		for(i=0;i<line.length;i++)
		{
			if(i>0)
			{
				output+="\n";
			}
			fmt=line[i];
			while(match=FREGEXP.exec(fmt))
			{
				var sign="";
				var pad=" ";

				if(!_empty(match[1])) // the left part
				{
					// You can't add this blindly because mozilla set the value to <undefined> when
					// there is no match, and we don't want the "undefined" string be returned !
					output+=match[1];
				}
				if(!_empty(match[2])) // the sign (like in %-15s)
				{
					sign=match[2];
				}
				if(!_empty(match[3])) // the "0" char for padding (like in %03d)
				{
					pad="0";
				}

				var width=match[4];	// the with (32 in %032d)
				var prec=match[6];	// the precision (10 in %.10s)
				var type=match[7];	// the parameter type

				fmt=match[8];

				if(index>=av.length)
				{
					output += "[missing parameter for type '"+type+"']";
					continue;
				}

				var val=av[index++];

				switch(type)
				{
				case "d":
					output += _printf_num_(val,10,pad,sign,width);
					break;
				case "o":
					output += _printf_num_(val,8,pad,sign,width);
					break;
				case "x":
					output += _printf_num_(val,16,pad,sign,width);
					break;
				case "X":
					output += _printf_num_(val,16,pad,sign,width).toUpperCase();
					break;
				case "c":
					output += String.fromCharCode(parseInt(val,10));
					break;
				case "s":
					output += _printf_str_(val,pad,sign,width,prec);
					break;
				case "f":
					output += _printf_float_(val,pad,sign,width,prec);
					break;
				default:
					output += "[unknown format '"+type+"']";
					break;
				}
			}
			output+=fmt;
		}
		return output;
	}

})(jQuery);

(function($) {
    var _alec_s_litebox = {
        init            : false,
        defaults        : {
            width   : 400,
            height  : 200
        },
        open            : function(options){
            if(this.init){
                this.close();
            }
            var actiontype ;
            if(options.url != undefined){actiontype = 'url'}
            else if(options.urlpost != undefined){actiontype = 'urlpost'}
            else if(options.text != undefined){actiontype = 'text'}
            else if(options.image != undefined){actiontype = 'image'}
            this.props  = {
                width       : options.width || this.defaults.width,
                height      : options.height || this.defaults.height,
                action      : options.url || options.text || options.img || null,
                actiontype  : actiontype,
                oncomplete  : options.oncomplete || function(){void(null);}
            };
            //alert(this.props.height);
            this.init       = true;
            this.overlay_id = 'overlay_' + $.srand(10);
            this.holder_id  = 'holder_' + $.srand(10);
            $('body').append($.sprintf('<div id="%s" class="litebox_overlay"></div>', this.overlay_id));
            $('#'+this.overlay_id).hide();
            $('#'+this.overlay_id).css('opacity',.3);
            if(/MSIE/.test(navigator.userAgent)){
    			$('#'+this.overlay_id).css('filter','alpha(opacity=30)');
    		}
    		$('body').append($.sprintf('<div id="%s" class="litebox_holder"></div>', this.holder_id));
    		$('#'+this.holder_id).hide();
    		$('#'+this.holder_id).css('width',this.props.width);
    		$('#'+this.holder_id).css('height',this.props.height);
    		this.fit();
    		$('#'+this.overlay_id).bind('click',function(){$.close_litebox();});
    		$(window).bind('scroll',function(){_alec_s_litebox.fit();});
    		$(window).bind('resize',function(){_alec_s_litebox.fit();});
    		this.fix();
            $('#'+this.overlay_id).fadeIn('slow');
            $('#'+this.holder_id).fadeIn('normal');
            switch(this.props.actiontype){
                case 'urlpost':
                    //Dumper.alert(options)
                    $('#'+this.holder_id).ldp({
                        url : options.urlpost,
                        data: options.data,
                        oncomplete:
                            (typeof options.oncomplete == 'function' ? options.oncomplete() : void(null))
                    });
                    break;
                case 'url':
                    $('#'+this.holder_id).ld({url:this.props.action,oncomplete:this.props.oncomplete,
                        height:this.props.height});
                    break;
                case 'text':
                        $('#'+this.holder_id).html(this.props.action);
                    break;
                case 'image':
                        alert('Image loading unsupported yet!');
                    break;
                default: break ;
            }
        },
        dim             : function(){
            return  {
                owidth      : $(window).width(),
                oheight     : $(document).height(),
                hleft       : ($(window).width()/2) + ($(window).scrollLeft()) - (this.props.width/2) ,
                htop        : ($(window).height()/2) + ($(window).scrollTop()) - (this.props.height/2)
            }
        },
        close           : function(){
            this.init = false ;
            this.unfix();
            $('#'+this.overlay_id).unbind();
            $(window).unbind();
            $('#'+this.holder_id).remove();
            $('#'+this.overlay_id).remove();
        },
        fit             : function(){
            var dim = this.dim();
            $('#'+this.overlay_id).css('width',dim.owidth);
            $('#'+this.overlay_id).css('height',dim.oheight);
            $('#'+this.holder_id).css('left',dim.hleft);
            $('#'+this.holder_id).css('top',dim.htop);
        },
        fix             : function(){
            if(/MSIE/.test(navigator.userAgent)){
                $('select').css({ visibility: "hidden" });
            }
		},
        unfix           : function(){
            if(/MSIE/.test(navigator.userAgent)){
                $('select').css({ visibility: "visible" });
            }
        }
    };
	$.litebox = function(options){
	   _alec_s_litebox.open(options);
	};
	$.close_litebox = function(){
	   _alec_s_litebox.close();
	};
	$.get_litebox = function(){
	    return $('#'+_alec_s_litebox.holder_id);
	};
})(jQuery);

var spin_round,spin,spin_container,email_pattern;

(function($) {
    spin_round      = '<img src="/img/spinners/loading-circ.gif" width="16" height="16" />';
    spin            = '<img src="/img/spinners/spinner.gif" width="86" height="10" />';
    spin_container  = '<div class="spin_container">%s</div>';
    spin_warn       = '<div class="spin_warn">Loading, please wait...</div>';
    email_pattern   = /^(([\_-]*[\w\xd6\xdc\xc4\xf6\xfc\xe4\xdf]+[\_-]*)+\.)*([\_-]*[\w\xd6\xdc\xc4\xf6\xfc\xe4\xdf]+[\_-]*)+@(([\_-]*[\w\xd6\xdc\xc4\xf6\xfc\xe4\xdf]+[\_-]*)+\.)+([A-Za-z]{2,4}){1}$/;
    $.is_email = function(s){
	   return email_pattern.test(s);
    }
    $.rand = function(x){
        var str = '';
        if(!x) {return str;}
        while(x){str += Math.floor(Math.random()*10);x--;}
        return str;
    };
    $.srand = function(x){
        var str = '';
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    	for (var i = 0; i < x; i++) {
            var y = Math.floor(Math.random() * chars.length);
            str += chars.substring(y,y+1);
        }
        return str;
    }
    $.require = function(f){
    	var e = document.createElement('SCRIPT');
    	e.setAttribute("src", f);
    	e.setAttribute("type",'text/javascript');
    	$('head')[0].appendChild(e);
    }
    $.fn.ld = function(o){
        return this.each(function(){
            var rem_h = $(this).css('height') || 'auto';
            var h = $(this).height();
            //$(this).css('height', h);
            $(this).css('height', 'auto');
            //$(this).html($.sprintf(spin_container, spin_round));
            $(this).html($.sprintf(spin_container, ((typeof o.no_warn == 'undefined') ? spin_warn : '') + spin_round));
            var _this = this;
            $('.spin_container img').each(function(){
                //$(this).css('top', (h/2) - ($(this).attr('height')/2));
            });
            $.get(o.url, {}, function(data){
                $(_this).html(data);
                $(_this).css('height', o.height || 'auto');
                if(o.oncomplete != undefined){
                    o.oncomplete();
                }
            });
        });
    }
    $.fn.ldp = function(o){
        return this.each(function(){
            var rem_h = $(this).css('height') || 'auto';
            var h = $(this).height();
            //$(this).css('height', h);
            $(this).css('height', 'auto');
            //$(this).html($.sprintf(spin_container, spin_round));
            $(this).html($.sprintf(spin_container, ((typeof o.no_warn == 'undefined') ? spin_warn : '') + spin_round));
            var _this = this;
            $('.spin_container img').each(function(){
                //$(this).css('top', (h/2) - ($(this).attr('height')/2));
            });
            $.post(o.url, o.data, function(data){
                    $(_this).html(data);
                    $(_this).css('height', 'auto');
                    if(o.oncomplete != undefined){
                        o.oncomplete();
                    }
            });
        });
    }
    $.gff = function(id){
        var o = {};
        $('#'+id).find('input, select, textarea').each(function(){
            var name = $(this).attr('name');
            var val = $(this).val();
            if(!name){
                return;
            }
            if(/^_/.test(name)){
                return;
            }
            o[name] = val;
        });
        return o;
    }
})(jQuery);



$.PA_CROPPER = new function(){

    this.CROPDATA = '';

    this.settings = {
        container: 'product_preview',
        crop_target:'crop_target',
        init_width: 0,
        init_height: 0,
        rem_cont: '',
        url:'',
        on_open     : function(){}, // executed after funcs and div loaded
        on_set      : function(c){
            $('#c_x1').val(c.x);
            $('#c_y1').val(c.y);
            $('#c_x2').val(c.x2);
            $('#c_y2').val(c.y2);
            $('#c_w').val(c.w);
            $('#c_h').val(c.h);
        },
        on_cropend  : function(){}, // executed after crop end
        on_discard  : function(){}
    };

    this.set = function(k, v){
        this.settings[k] = v;
    };

    this.unset = function(k, v){
        delete this.settings[k] ;
    };

    this.open = function(){
        this.settings.rem_cont = $('#'+this.settings.container).html();
        var z = this.settings ;
        $('#'+this.settings.container).ld({
            url:this.settings.url,
            oncomplete:function(){
                $.PA_CROPPER.settings.on_open();
                try{
                    $('#'+z.crop_target).unbind().Jcrop({
                        onSelect:    z.on_set ,
                        bgColor:     'black' ,
                        bgOpacity:   .4 ,
                        setSelect:   [ $('#c_x1').val(), $('#c_y1').val(), $('#c_x2').val(), $('#c_y2').val() ] ,
                        aspectRatio: $('#f_w').val() / $('#f_h').val()
                    });
                }
                catch(e){}
            }
        });
    };

    this.cancel = function(){
       $('#'+this.settings.container).html(this.settings.rem_cont);
       bind_cropper_button();
    };

    this.discard = function(){
        $.PA_CROPPER.settings.on_discard();
    };

    this.update = function(){
        $.PA_CROPPER.CROPDATA = $.sprintf('%d,%d,%d,%d,%d,%d',
            $('#c_x1').val(),$('#c_y1').val(),$('#c_x2').val(),$('#c_y2').val(),$('#c_w').val(),$('#c_h').val()
        );
        $.PA_CROPPER.settings.on_cropend();
    };

}


$.PA_FILECHOOSER = new function(){
    this.settings = {
        selected_file   : 0,
        selected_folder : 0,
        container       : '#product_options',
        helpindex       : 18
    };
    this.set = function(k, v){
        this.settings[k] = v;
    }
    this.set_container = function(id){
        this.settings.container = '#'+id;
    }
    this.get = function(k){
        if(this.settings[k] == undefined){
            return null;
        }
        else {
            return this.settings[k];
        }
    }
    this.get_container = function(){
        return this.settings.container ;
    }
    this.prepare_dataset = function(){
        var app_data = {};
        for(k in this.settings){
            if(typeof this.settings[k] == 'function'){
                continue;
            }
            app_data['data[FileWidget]['+k+']'] = this.settings[k];
        }
        return app_data;
    }
    this.open_pane = function(){
        $(this.get('container')).ldp({
            url         : $.sprintf('/products/widget_picture_chooser/?rand=%s&helpindex=%s', $.srand(8), $.PA_FILECHOOSER.get('helpindex')),
            data        : $.PA_FILECHOOSER.prepare_dataset(),
            oncomplete  : function(){
                $.PA_FILECHOOSER.open_folder($.cookie('last_folder') || 0);
            }
        });
    }
    this.open_folder = function(f){
        this.set('selected_folder', f);
        $.cookie('last_folder',f);
        $('#file_chooser_pane').ldp({
            url     : $.sprintf('/products/widget_picture_chooser_files/?rand=%s&helpindex=%s', $.srand(8), $.PA_FILECHOOSER.get('helpindex')),
            data    : $.PA_FILECHOOSER.prepare_dataset()
        });
    }
    this.open_only_folder = function(div_id){
        return $('#'+div_id).ldp({
            url     : $.sprintf('/products/widget_picture_multifolder/?rand=%s&helpindex=%s', $.srand(8), $.PA_FILECHOOSER.get('helpindex')),
            data    : $.PA_FILECHOOSER.prepare_dataset(),
            oncomplete  : function(){
                if(typeof $.PA_FILECHOOSER.settings.document_loaded == 'function'){
                    $.PA_FILECHOOSER.settings.document_loaded();
                }
            }
        });
    }
    this.set_file_callback = function(fn){
        this.set('file_click_callback', fn);
    }
    this.set_document_loaded = function(fn){
        this.set('document_loaded', fn);
    }

}

function alecs_tabbed_interface(){
    $('#tabs div.tabdiv').hide(); // Hide all divs
    $('#tabs div.tabdiv:first').show(); // Show the first div
    $('#tabs ul li:first').addClass('tab-active'); // Set the class of the first link to active
    $('#tabs ul li a').click(function(){ //When any link is clicked
        $('.hidable').hide();//hide any othee shit we need to hide
        $('.clearable').html('');//clear any other shit we need to clear
        $('#tabs ul li').removeClass('tab-active'); // Remove active class from all links
        $(this).parent().addClass('tab-active'); //Set clicked link class to active
        var currentTab = $(this).attr('href'); // Set variable currentTab to value of href attribute of clicked link
        $('#tabs div.tabdiv').hide(); // Hide all divs
        $(currentTab).show(); // Show div with id equal to variable currentTab
        return false;
    });
}

function alecs_font_chooser(){
    //alert($('#'+select_id).val())
    $('._fontchooser').unbind().css('cursor', 'pointer').bind('click', function(){
        var o = $(this).attr('rel');
        $.litebox({
            url : '/pureactions/get_font_list/'+o,
            width:500,
            height:350,
            oncomplete : function(){
                $('.close_litebox').unbind().bind('click', function(){$.close_litebox()});
                $('._fontchooser_font').unbind().css('cursor', 'pointer').bind('click', function(){
                    $('#'+o).val($(this).attr('alt'));
                    $.close_litebox();
                });
            }
        });
    });
}

function alecs_font_size(){
    //alert($('#'+select_id).val())
    $('._fontsizechooser').unbind().css('cursor', 'pointer').bind('click', function(){
        var o = $(this).attr('rel');
        $.litebox({
            url : '/pureactions/get_font_size/'+o,
            width:500,
            height:200,
            oncomplete : function(){
                $('.close_litebox').unbind().bind('click', function(){$.close_litebox()});
                $('._fontchooser_size').unbind().css('cursor', 'pointer').bind('click', function(){
                    $('#'+o).val($(this).attr('rel'));
                    $.close_litebox();
                });
            }
        });
    });
}

function bind_links_main(){
    // work out system messages
    $('.required label').attr('title', 'This is the required field');
    if($('#flashMessage').length > 0){
        $('#flashMessage').fadeIn(2000).fadeOut(4000);
    }
}

function isset(varname){
    return(typeof(window[varname])!='undefined');
}


/**
 * Product for helper to store local values
*/
$.PA_FORM = new function(){
    this.settings = {
        form_name   : 'product_form'
    }
    this.isset = function(k){
        var o = this.keys(k);
        //return typeof $('#'+this.settings.form_name).find('#'+o.id) != 'undefined';
        return $('#'+this.settings.form_name).find('#'+o.id).length > 0;
    }
    this.keys = function(k){
        var c = k.split('.');
        var name    = 'data';
        var id      = 'PAFORM';
        while(d = c.shift()){
            name+= $.sprintf('[%s]', d);
            id  += $.sprintf('_%s', d);
        }
        return {name:name, id:id};
    }
    this.set = function(k, v){
        var o = this.keys(k);
        if(!this.isset(k)){
            $('#'+this.settings.form_name).append($.sprintf('<input type="hidden" id="%s" name="%s">', o.id, o.name));
        }
        $('#'+this.settings.form_name).find('#'+o.id).val(v);
    }
    this.get = function(k){
        var o = this.keys(k);
        return $('#'+this.settings.form_name).find('#'+o.id).val();
    }
    this.unset = function(k){
        var o = this.keys(k);
        if(this.isset(k)){
            $('#'+this.settings.form_name).find('#'+o.id).remove();
        }
    }
    this.restore_data = function(form_id){
        var a = $('#'+form_id).html();
        $('#'+form_id).html('');
        $('#'+this.settings.form_name).html(a);
    }
}

function ome_makemebig(o){
    $(o).attr('src', $(o).attr('src').replace('thumb_small', 'thumb_big'))
        .attr('width', 400).attr('height',400).css('border', '1px solid black');
}

function ome_makemesmall(o){
    $(o).attr('src', $(o).attr('src').replace('thumb_big', 'thumb_small'))
        .attr('width', 64).attr('height', 64).css('border', 'none');
}


// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
}

jQuery(function($){
    bind_links_main();
});

