var Accessories = {
	datepicker: function(el,format){
		$(document).ready(function(){$(el).datepicker({ dateFormat: format});});
	},
	include:function(filename){
    	document.write('<' + 'script');
    	document.write(' language="javascript"');
    	document.write(' type="text/javascript"');
    	document.write(' src="' + filename + '">');
    	document.write('</' + 'script' + '>');
	}
};

var Adv = {
	SetType: function(id){
		$(document).ready(function(){
	 		if(!id) id = 1;
	 		$('.type:not(.type_'+id+')').hide();
	 	});
	},
	ChangeType: function(id){
		if(id){
			$('.type').hide();
			$('.type_'+id).show();
		}
	},
	Move: function(){
		$(document).ready(function(){
			$(".sortable").sortable({ opacity: 0.6, cursor: 'move',handle: '',forceHelperSize: true,  update: function(){
				var data = $(this).sortable("serialize"); 
				notice_load();
				$.post(URL_ADV_MOVE, data, function(theResponse){
					theResponse = Text.RemoveWS(theResponse);
					remove_notice_load();
					$('body').prepend(theResponse);
				});
			}});
		});
	}
};

var Text = {
	/* Remove white space */
	RemoveWS: function(str){
		if(str){return str.replace(/^\s*|\s*$/g,'');
		}else{return str;}
	}
};

var Page = {
	FooterPosition: function(){
		var body_height = $('body').height();
		var wrapper_height = $('#page_body').height();
		if(body_height-wrapper_height>50){
			$('body').css('position','relative');
			$('#footer').css({'position':'absolute','bottom':'0'});
		}else{
			$('body').css('position','static');
			$('#footer').css('position','static');
		}
	},
	CheckWindowHeight: function(){
		$(window).resize(function(){
			Page.FooterPosition();
		});
		$('#page_body').bind("resize",function(){
			//TODO:zlikwidowac efekt stroboskopu.
			Page.FooterPosition();
		});
		$('#page_body').bind("DOMSubtreeModified",function(){
			//TODO:zlikwidowac efekt stroboskopu.
			Page.FooterPosition();
		});
		
	}
};


var Search = {
	SetNavigationEvent: function(){
		$(document).ready(function(){
			$('.c').change(function(){
				$('.c').attr('checked',false);
				$('.c').next('label').removeClass('label_red');
		 		$(this).attr('checked',true);
				$(this).next('label').addClass('label_red');
			});
			$('.k').change(function(){
				$('.k').attr('checked',false);
				$('.k').next('label').removeClass('label_red');
		 		$(this).attr('checked',true);
				$(this).next('label').addClass('label_red');
			});
			$('.search_big').keypress(function(){
				$('.search_big').not(this).val('');
			});        
		});
	}
};


var Categories = {
	SetTree: function(el){
		var self = this;
		$(' li:last-child').addClass('last');
		$(el+' li a.expand').attr({'title':SHOW_SUBDIRECTORIES,'alt':SHOW_SUBDIRECTORIES});
		$(el+' li a.collapse').attr({'title':HIDE_SUBDIRECTORIES,'alt':HIDE_SUBDIRECTORIES});
		$(el+' li a.empty').attr({'title':'','alt':''});
		$(el+' li > a').bind('click', function(){
			self.ShowCat($(this).parent().attr('id').replace('li_',''));
			return false;
		});
		$(el+' li .item > a').bind('click', function(){
			if(!$(this).parent().hasClass('no_active')){				id = $(this).parent().parent().attr('id').replace('li_','');
				self.ShowProducts(id);				var a = $('#li_'+id+' > a');				if($(a).hasClass('expand')){					self.ShowCat(id);				}
			}
			return false;
		});
	},
	/*Show categories in a tree*/
	ShowCat: function(id){ 
        if(id){
        	var d = $('#li_'+id+' > .d');
        	var a = $('#li_'+id+' > a');
        	if($(a).hasClass('empty')){return false;}
			if($(a).hasClass('collapse')){Categories.HideCat(id);}
			else{
				if($(a).hasClass('expand')){
				$.ajax({method: 'get',url: URL_SHOW_CAT+'&id='+id,success: function(s){
					if (s.length>3){
						$(d).html(s).show();
						$(a).attr({
							'class':'collapse',
							'title':HIDE_SUBDIRECTORIES,
							'alt':HIDE_SUBDIRECTORIES
						});
						Categories.SetTree('#li_'+id);
					}
					remove_notice_load();
					},beforeSend: function(){notice_load();}
				});
				}
			}
		}
    },
    /*Hide categories in a tree*/
    HideCat: function(id){
    	$('#li_'+id+' > a').attr({
    		'class':'expand',
    		'title':SHOW_SUBDIRECTORIES,
			'alt':SHOW_SUBDIRECTORIES
    	});
		$('#li_'+id+' > .d').html('').hide();
    },
    ShowProducts: function(id){
		if(id){
			$.ajax({method: 'get',url: URL_SHOW_PRODUCTS+'&id='+id,
			success: function(s){
				Categories.RemoveActive();
				$('#li_'+id+' > .item > a').addClass('selected');
				$('.zoomimage').remove();
				$('.content_right').html(s);				if(!$('#li_'+id).hasClass('first')){
					Categories.GoToTop();				}
				remove_notice_load();
			},
			beforeSend: function(){
				notice_load();
			}
		});
		}	
	},
	RemoveActive: function(){
		$('ul.roots li a.selected').removeClass('selected');
	},
	GoToTop: function(){
		if($('body').scrollTop() > 225 || $('html').scrollTop() > 225){$('html, body').animate({scrollTop:0}, 'slow');}
	}
};

function float(el){
	var float=/^[0-9\.]*$/i;
	var not_float=/[^0-9\.]+/g;
	var value = $(el).val();
	if(value.match(float)){$(el).val(value);
	}else{$(el).val(value.replace(not_float,""));}
}

function integer(el){
	var format=/^[0-9]*$/i;
	var not_format=/[^0-9]+/g;
	var value = $(el).val();
	if(value.match(format)){$(el).val(value);
	}else{$(el).val(value.replace(not_format,""));}
}


/*create function*/
function create_function (args, code) {
     try{  
        return Function.apply(null, args.split(',').concat(code));
     }
     catch (e) {
         return false;     }
}

/*remove MSWord Chars*/
$(document).ready(function(){
	$(function(){
    	$("textarea").change(function(){
        	$(this).val(removeMSWordChars(this.value));
   	 	});
	});
});


/* helper method*/
function in_array(what, where){
    var a = false;
	if (where) {
		for (var i = 0; i < where.length; i++) {
			if (what == where[i]) {
				return (i+1);
			}
		}
	}
	return false;
}

/* resize window width*/
function check_window_width(){
	if($(window).width()< 1260){
		$('#belka').css('width','1260px');
		$('#baner').css('width','1260px');
		$('#footer').css('width','1260px');
	}else{
		$('#belka').css('width','100%');
		$('#baner').css('width','100%');
		$('#footer').css('width','100%');
	}
}
		
/* check max length */
function ismaxlength(obj,mlength){
	mlength = (!mlength)?($(obj).attr('maxlength')? parseInt($(obj).attr('maxlength')) : ""):mlength;
	//if ($(obj).attr('maxlength') && $(obj).val().length > mlength) {
		setCharacters(obj,mlength);
		
	//}else if(obj.getAttribute){
	//	setCharacters(obj,mlength);
	//}
}

function setCharacters(obj,mlength){
	var name = $(obj).attr('id');
	if(!$('#'+name+'_characters').html()){
		$('#'+name).after('<div name="'+name+'_characters" id="'+name+'_characters" class="maxlength_characrers">characters:<b '+( ($(obj).val().length>mlength)?'style="color:#dd0000;"':'')+'>'+$(obj).val().length+'</b>, maximum:<b>'+mlength+'</b></div>');
		if($(obj).val().length>mlength){
			$('#'+name+'_characters').append('<div class="error" id="'+name+'_error">Too many characters introduced, extra characters will be truncated.</div>');
		}else{$('#'+name+'_error').remove();}
	}else{
		$('#'+name+'_characters').html('characters:<b '+( ($(obj).val().length>mlength)?'style="color:#dd0000;"':'')+'>'+$(obj).val().length+'</b>, maximum:<b>'+mlength+'</b>');
		if($(obj).val().length>mlength){
			$('#'+name+'_characters').append('<div class="error" id="'+name+'_error">Too many characters introduced, extra characters will be truncated</div>');
		}else{$('#'+name+'_error').remove();}
	}
}

/* ------------------*/
function removeMSWordChars(str) {
    var myReplacements = new Array();
    var myCode, intReplacement;
    myReplacements[8216] = 39;
    myReplacements[8217] = 39;
    myReplacements[8220] = 34;
    myReplacements[8221] = 34;
    myReplacements[8212] = 45;
    for(c=0; c<str.length; c++) {
        var myCode = str.charCodeAt(c);
        if(myReplacements[myCode] != undefined) {
            intReplacement = myReplacements[myCode];
            str = str.substr(0,c) + String.fromCharCode(intReplacement) + str.substr(c+1);
        }
    }
    return str;
}
var loader_count = 0;
function notice_load(){
	if($('#body_black_white').css('display') != 'block' && $('#body_black').css('display') != 'block'){
		$('body').prepend('<div id="body_black_white" class="body_black"></div><div id="loader"></div>');
		$('#body_black_white').css('height',''+$(document).height()+'px');
		$('#body_black_white').css('display','block');
		$width = $(window).width()/2;
		$height = $(window).height()/2;
		$('#loader').css({'left':$width+'px', 'top':$height+'px'});
	}
	loader_count++;
}

function remove_notice_load(){
	if(loader_count == 1){
	$('#body_black_white').remove();
	$('#loader').remove();
	}
	loader_count--;
}


function notice(value){
	$('#body_black_white').remove();
	$('#loader').remove();
    humanMsg.setup();
    humanMsg.displayMsg('<div><div class="msg_text"><div class="border_blue"><div>' + value + '</div></div></div><input type="button" name="msg_next" id="msg_next" class="msg_next" value="Close"/></div>');
    $('#msg_next').click(humanMsg.removeMsg);
    $('#body_black').click(humanMsg.removeMsg);
    
    
}

function load_url(url){
    if (url) 
        document.location.href = url;
}

function delete_item(id, url, element, method){
    if (id && url) {
        $.ajax({
            method: method,
            url: url + "&id=" + id,
            success: function(s){
                $(element + id).slideUp();
                $(element + id).remove();
                remove_notice_load();
            },
            beforeSend: function(){
                notice_load();
            }
        });
    }
}

function get_categories(element, box){
    $('#show_all').attr('checked', false);
    notice_load();
    $('#category_search_form').ajaxSubmit(function(s){
        $('#' + box).html(s);
        remove_notice_load();
        return false;
    });
    return false;
}

function update_db_table_category(url){
    $.ajax({
        method: 'get',
        url: url,
        success: function(s){
            $('body').prepend(s);
            remove_notice_load();
        },
        error: function(){
            notice('Update has not been completed. Repeat the operation.');
        },
        beforeSend: function(){
            notice_load();
        }
    });
}

function unable(element){
    $(element).attr('disabled', false);
}


function check_options(el_val){
    if (el_val == 5) {
        $('.supplier').show();
    }
    else {
        $('.supplier').hide();
        $('#supplier_type input').attr('checked', false);
    }
}

/* change status */
function change_status(id,value,URL_CHANGE_STATUS){
	if(value){
		$.ajax({
        method: 'get',
        url: URL_CHANGE_STATUS+"&id="+id+"&value="+value,
        success: function(s){
            remove_notice_load();
            s = Text.RemoveWS(s);
            if(!s){
            	if(value == 1){
            		$('#tr_'+id).removeAttr('class');
            		update_html_products_left('-1');
            	}else{
            		$('#tr_'+id).attr('class','tr_red');
            		update_html_products_left('1');
            	}
            }else{
            	$('body').prepend(s);
            	if(value == 1){
            		$('#change_status_product_'+id).val('2');
            	}else{
            		$('#change_status_product_'+id).val('1');
            	}
            }
        },
        beforeSend: function(){
            notice_load();
        }
    });
	}
}
/* method for update products left box */
function update_html_products_left(v){
	var products_left = $('#products_left').html();
	if(products_left){
		products_left = parseInt(products_left)+parseInt(v);
		$('#products_left').html(products_left);
	}
}

function check_count(name,mlength){
		if($('#'+name).val().length > mlength){
			return confirm('Too many characters introduced in '+name.toUpperCase()+', extra characters will be truncated.');
		}else{return true;}
}
	
/* check category count */
function check_category_count(message){
	var count=0;
	$('.id_category').each(function(){
		count++;
	});
	if(!count){
		alert(message);
		return false;
	}
	return true;
}

/* for search */
function browse_category(){
	$('.categories_manual').hide();
	$('.search_panel').css('background'," url('./public/graf/search_bg.png') no-repeat 0px -116px");
	$('#content_center').css('height','auto');
	$('.menu_left').slideDown('fast');
}

function show_missing_category(){
	if($('#send_form').css('display') == 'none')$('#send_form').show();
	else $('#send_form').hide();
}
