jQuery.fn.init_body = function() {
    return this.each(function() {
        var id = jQuery(this).attr('id');
        jQuery(this).hover(
            function() {
                jQuery(this).addClass('current');
            },
            function() {
                $(this).removeClass('current');
            }
        );
        jQuery(this).find('.status').click(function(){embexp.status(id)});
        jQuery(this).find('.but_del').click(function(){embexp.del(id)});
        jQuery(this).find('.but_edit').click(function(){embexp.edit(id)});
        jQuery(this).find('.butt-ac').children('i').click(function(){embexp.addtocart(id)});
        jQuery(this).find('.butt-aw').children('i').click(function(){embexp.addtowishlist(id)});
        jQuery(this).find('.butt-vt').children('i').click(function(){embexp.vote(id)});
    });
}
$(document).ready(function() {
    //-- init
    $('.id').init_body();
    $('input#labelsearch').click( function(){$(this).val('').css('color','#000')}).autocomplete(base_url,{parameters:{'cm':'autocomplete','vl':glb_object_id}});
	$('input#designsearch').click( function(){$(this).val('').css('color','#000')}).next().click( function(){location.href=base_url+'?vl='+$(this).prev().attr('value'); } );
	$('#re').click( function() { embexp.re('form','show'); });
	$('#butt-hm').click( function(){location.href=base_url;} );
	$('#butt-cart').click( function(){location.href=base_url+'?com=basket';} );
	$('#butt-wl').click( function(){location.href=base_url+'?com=wishlist';} );
	$('#butt-checkout').click( function(){location.href=base_url+'?com=basket&cm=order';} );
	$("button[rel]").overlay({
		oneInstance: false,
		closeOnClick: false,
		effect: 'apple'
	});
	$("#but-colorchart").overlay({
		oneInstance: false,
		closeOnClick: false,
		effect: 'apple',
		onLoad: function() {
			embexp.colorchart('get');
		}
	});
	$('#test').click( function(){
		$('#dialog').dialog({
			bgiframe: true,
			height: 300,
			modal: true
		});
		$('#dialog').dialog();
	});
    if ( sess == 1 ) {
    }
    if(glb_page) {
    	if (ret = glb_page.match(/^(free|votelist|membership|deals|designs)$/ig)){
    		$('.img-'+ret).addClass('img-current');
    	}
    }
});//---
var embexp=function(){
    var rtn={
    	re:function() {
    		if (sess!=1) {embexp.signin();return;}
    		jQuery('.re-h').toggle();
    		jQuery('#re-f').toggle();
    		return false;
    	},
    	changelocation:function(href) {
    		location.href=href;
    	},
        signin:function() {
            embexp.changelocation(base_url+'?com=signin');
            return false;
        },
        status:function(vl) {
            if (sess!=1) {embexp.signin();return;}
            var j_bdy=$('#'+vl), j_sr=j_bdy.children('.sr')
            j_sr.html('Loading...').addClass('service_ajax');
            $.getJSON(base_url,{'vl':vl,'cm':'status'},function(json){
                j_sr.html('').removeClass('service_ajax');
                if (json.type=='ok') {
                	if (json.results==1) {
                		j_bdy.find('.status').attr('class','status status_on');
                	} else {
                		j_bdy.find('.status').attr('class','status status_off');
                	}
                }
            });
            return false;
        },
        colorchart:function(m,d) {
        	var div=$('#colorchart').find('p');
        	switch(m) {
        		case 'get':
        			break;
        	}
            $.getJSON(base_url,{'vl':glb_object_id,'cm':'colorchart','type':'get','thread':d},function(json){
            	if (json.type=='ok') {
            		div.html(json.data);
            	}
            });
        	return false;
        },
        tag:function(m,d) {
        	var div;
        	switch(m) {
        		case 'add':
        			div=$('#tag');
        			d=div.addClass('autocomplete-loading').attr('value');
        			break;
        		case 'delete':
        			div=$('#tag-'+d).html('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').addClass('loading');break;
        	}
            $.getJSON(base_url,{'vl':glb_object_id,'cm':'tag','type':m,'tag':d},function(json){
            	if (json.ret=='add') {
            		div.removeClass('autocomplete-loading').attr('value','');
            		if (json.type=='ok'){
            			div=$('#idtags');
            			div.html(div.html()+json.data);
            		}
            	}
                if (json.ret=='deleted') {div.html('').removeClass('loading').addClass('');}
            });
        	return false;
        },
        addtocart:function(vl) {
        	if (sess!=1) {embexp.signin();return;}
            var bdy=$('#'+vl);
            var div=bdy.find('.butt-ac');
            div.html('Loading...').addClass('loading');
            $.getJSON(base_url,{'vl':vl,'com':'basket','cm':'add','ret':'json'},function(json){
                if (json.type=='ok') {
                	div.html(json.results).removeClass('loading').addClass('ok');
                	$('#butt-cart b').html(++glb_cart_count);
                }
            });
            return false;
        },
        addtowishlist:function(vl) {
        	if (sess!=1) {embexp.signin();return;}
            var bdy=$('#'+vl);
            var div=bdy.find('.butt-aw');
            div.html('Loading...').addClass('loading');
            $.getJSON(base_url,{'vl':vl,'com':'wishlist','cm':'add','ret':'json'},function(json){
                if (json.type=='ok') {
                	div.html(json.results).removeClass('loading').addClass('ok');
                }
            });
            return false;
        },
        vote:function(vl) {
        	if (sess!=1) {embexp.signin();return;}
            var bdy=$('#'+vl);
            var div=bdy.find('.butt-vt');
            div.html('Loading...').addClass('loading');
            $.getJSON(base_url,{'vl':vl,'cm':'vote','type':'free'},function(json){
            	div.html('<i></i>+'+json.results).removeClass('loading').addClass('ok');
            });
            return false;
        },
        del:function(vl) {
            if (sess!=1) {embexp.signin();return;}
            if (confirm('Delete ?') ) {embexp.changelocation(base_url+'?vl='+vl+'&cm=delete');}
            return false;
        },
        edit:function(vl) {
            if (sess!=1) {embexp.signin();return;}
            embexp.changelocation(base_url+'?vl='+vl+'&cm=edit');
            return false;
        },
        form:function(f,n) {
            var mess='min 5 characters.';
            if (n=='re') mess='Your answer needs to be at least 5 characters long.';
            if (f.SubBOX.value.length<5) alert(mess);
            else f.submit()
        }
    };
    return rtn
}();
/**/
jQuery.fn.autocomplete = function(url,settings ) {
	//do it for each matched element
	return this.each( function() {
		var textInput = $(this);
		textInput.after('<input type=hidden name="' + textInput.attr("name") + '"/>').attr("name", textInput.attr("name") + "_text");
		var valueInput = $(this).next();
		valueInput.after('<ul class="labelsearch"></ul>');
		///var list = valueInput.next().css({top: textInput.offset().top + textInput.outerHeight(), left: textInput.offset().left, width: textInput.width()});
		var list = valueInput.next();
		var oldText = '';
		var typingTimeout;
		var size = 0;
		var selected = 0;
		//provide default settings
		settings = jQuery.extend( {
		minChars : 1,
		timeout: 1000,
		after : null,
		before : null,
		validSelection : true,
		parameters : {'inputName' : valueInput.attr('name'), 'inputId' : textInput.attr('id')}
		} , settings);
		function getData(text) {
			window.clearInterval(typingTimeout);
			if (text != oldText && (settings.minChars != null && text.length >= settings.minChars)) {
				clear();
				if (settings.before == "function"){
					settings.before(textInput,text);
				}
				textInput.addClass('autocomplete-loading');
				settings.parameters.text = text;
				$.getJSON(url,settings.parameters,function(data) {
					var items = '';
					if (data) {
						size = data.length;
						for (i = 0; i < data.length; i++) { //iterate over all options
							for ( key in data[i] ) { //get key => value
								items += '<li value="' + key + '"><a href="'+base_url+'?com=taglist&tag='+data[i][key]+'">' + data[i][key].replace(new RegExp("(" + text + ")","i"),"<strong>$1</strong>") + '</a></li>';
							}
							list.html(items);
							//on mouse hover over elements set selected class and on click set the selected value and close list
							list.show().children().
							hover(function() { $(this).addClass("selected").siblings().removeClass("selected");}, function() { $(this).removeClass("selected") } ).
							click(function () { valueInput.val( $(this).attr('value') );textInput.val( $(this).text() ); clear(); });
						}
						if (settings.after == "function") {
							settings.after(textInput,text);
						}
					}
					textInput.removeClass('autocomplete-loading');
				});
				oldText = text;
			}
		}
		function clear() {
			list.hide();
			size = 0;
			selected = 0;
		}
		textInput.keydown(function(e) {
			window.clearInterval(typingTimeout);
			if(e.which == 27){//escape
				clear();
			} else if (e.which == 46 || e.which == 8){//delete and backspace
				clear();
				if (settings.validSelection) valueInput.val('');//invalidate previous selection
			}
			else if(e.which == 13){//enter
				if ( list.css("display") == "none"){//if the list is not visible then make a new request, otherwise hide the list
					getData(textInput.val());
				} else {
					clear();
				}
				e.preventDefault();
				return false;
			}
			else if(e.which == 40 || e.which == 9 || e.which == 38){//move up, down
				switch(e.which){
					case 40:
					case 9:
						selected = selected >= size - 1 ? 0 : selected + 1; break;
					case 38:
						selected = selected <= 0 ? size - 1 : selected - 1; break;
					default: break;
				}
				//set selected item and input values
				textInput.val( list.children().removeClass('selected').eq(selected).addClass('selected').text() );
				valueInput.val( list.children().eq(selected).attr('value') );
			} else {
				//invalidate previous selection
				if (settings.validSelection) valueInput.val('');
				typingTimeout = window.setTimeout(function() { getData(textInput.val()) },settings.timeout);
			}
		});
	});
};
