var labels = new Array("Title","Website URL","Short Description","Description","Address","City");
var checking = new Array("title","url","short_desc","descr","address","city");
$(document).ready(function(){
	$("#mng-articles").click(function(){Functions.load('articeslist');});
	$("#add-articles").click(function(){Functions.load('articeadd');});
	$("#mng-info").click(function(){Functions.load('infoedit');});
	$("#mng-link").click(function(){Functions.load('linkedit');});
	$("#mng-links").click(function(){Functions.load('linkslist');});
	$("#mng-photo").click(function(){Functions.load('photoedit');});
	$("#mng-addnewlink").click(function(){
		$("#loader").show();
		$("#response").hide();
		$.getJSON('cp.php?action=link_new',
			function(d){
				$("#loader").hide();
				$("#response").html(d.msg);
				$("#response").show();
			});
		});
});


var Functions = {
	error: function (msg) {
        $.prompt('<div class="error">ERROR:</div>' + msg);
    },
    success: function (msg) {
        $.prompt('<div class="success">SUCCESS:</div>' + msg);
    },
	uploader:function(id,div){
		Site.loadCSS('fileuploader');
		$.getScript('js/fileuploader.js',
			function(){
				var uploader = new qq.FileUploader({
					element: document.getElementById(div),
					action: 'cp.php',
					multiple: false,
					allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
					params: {
						lid: id,
						action: 'photoup'
					}
				});
			});
	},
	remove:function(action,id){
      var div = $("#field-" + id);
		$.prompt('<div class="error">CONFIRM:</div>Are you sure you want to delete this Link?', {
            'buttons': {
                'Delete': true,
                'Cancel': false
            },
            'callback': function(v, m) {
                if (v) {
                    $.get('cp.php?action='+action+'&id=' + id, function(o) {
                        Functions.success('Link Removed!');
                        var t = setTimeout("window.location = 'member.php';", 4000);
                    });
                } else {}
            }
        });
	},
	reloadit:function(v){
		var t = setTimeout("Functions.load('"+v+"');",3000);
	},
	load:function(loc){
		$('#response').animate({height:'hide'},
			function(){
				$('#loader').toggle();
				$.get('cp.php?action='+loc,
					function(d){
						$('#loader').toggle();
						$('#response').html(d).show();
					});
			});
	},
	linkform:function(){
		this.tooltips();
		TextCheck.check_it(checking,labels);
		$('#descr').bind('keyup click blur focus change paste',
				function(){
					Functions.wordCount(120, this, '#descr_counter', 'Ad Text');
			});
		$('#short_desc').bind('keyup click blur focus change paste',
				function(){
					Functions.wordCount(30, this, '#short_desc_counter', 'Ad Text');
			});
		$("#descr").markItUp(myBBcodeSettings);
		$('#country').change(
			function(){
				var val = $('#country option:selected').val();
				$.get('ajax.php?action=regions&cid='+val,
					function(d){
						$('#regions').html(d);
					});	
			});
		
		$("#adminform").validate({
			submitHandler: function(form) {
				var p1 = TextCheck.check_length('#short_desc');
				p1 = (!p1) ? false:TextCheck.check_length('#descr');
				p1 = (!p1) ? false:TextCheck.validate(checking,labels);
				if(p1){
					var values = $("#adminform").serialize();
					$('html, body').animate({scrollTop: $('#body').offset().top});
					$('#response').hide();
					$('#loader').show();
					
					$.getJSON('cp.php',values,
						function(d){
							$('#loader').hide();
							Site.success(d.msg);
							var t = setTimeout("window.location = 'member.php';", 4000);
							
						});
				}
			},
			rules: {
				title: {
					required: true,
					minlength: 3
				},
				cat: {
					required: true
				},
				url: {
					required: true,
					minlength: 3,
					url: true
				},
				short_desc: {
					required: true
				},
				descr: {
					required: true
				},
				phone: {
					required: true,
					phone: true
				}
			},
			messages: {
				url: {
					url: "Must be a valid full url. Be sure to include http:// at beginning."
				}
			}
		});
	},
	infoform:function(){
		$("#adminform").validate({
			submitHandler: function(form) {
				var values = $("#adminform").serialize();
				$('html, body').animate({scrollTop: $('#body').offset().top});
				$('#response').hide();
				$('#loader').show();
				$.getJSON('cp.php',values,
					function(d){
						$('#loader').hide();
						Site.success(d.msg);
						var t = setTimeout("Functions.load('infoedit');",2000);
					});
			},
			rules: {
				fname: {
					required: true,
					minlength: 3
				},
				lname: {
					required: true,
					minlength: 3
				},
				email: {
					required: true,
					email:true
				}
			}
		});
	},
	articleform:function(){
		this.loadCSS("markitup/skins/simple/style.css");
		this.loadCSS("markitup/sets/default/style.css");
		$.getScript("markitup/jquery.markitup.js",
			function(){
				$.getScript("markitup/sets/default/set.js",
					function(){
						$("#content").markItUp(myHtmlSettings);
					});
			});
		$("#adminform").validate({
			submitHandler: function(form) {
				form.submit();
				$('#response').hide();
				$('#loader').show();
			},
			rules: {
				title: {
					required: true,
					minlength: 3
				},
				content: {
					required: true
				}
			}
		});
	},
	framed_response:function(d){
		$('#loader').hide();
		$("#response").show().html('<h2>'+d.msg+'</h2>');
		var t = setTimeout("Functions.load('"+d.call+"');",5000);
	},
	loadCSS:function(c){
		$("head").append("<link >");
		css = $("head").children(":last");
		css.attr({
			rel:  "stylesheet",
			type: "text/css",
			href: c
		});	
	},
	selectC:function(){
		var total = 0;
		$("#caterror").html("");
		var current = [];
		$('#cat :selected').each(function(i, selectedObj){
		    total = total + 1;
		    if(total > 3){
			    $(selectedObj).attr('selected', false);
			    $("#cat option[2]").attr('selected', false);
			    $("#caterror").html("You may only choose 3 Categories.<br />When you submit the form, we will take the first 3 selections.");
		    }
		});
	},
	wordCount:function(limit, div, resp, label){
		var field = $(div);
		var val = field.val();
		var len = 0;
		if(val){
			var len = val.replace(/[^A-Za-z0-9 ]/g, "")
				.replace(/\s+/g, " ")
				.split(' ').length;
				
			var nval = val;
			var diff = limit - len;
			if (diff < 0) {
				if(len >= limit){
					nval = val.split(/(\s+)/, (limit*2)-1).join('');
				}
				field.val(nval);
			}
		}
		$(resp).html(len+' out of ('+limit+') words left');
	},
	tooltips:function(div){
		$.getScript('js/jquery.simpletip.js',
			function(){
				$("#response span.ttip").each(
				   	function(){
				    	var id = this.id;
				    	$("#"+id).simpletip({ 
					    	content: $("#"+id+" div.tooltip").html(),
					    	fixed: true, 
					    	position: 'bottom,right' 
					    });
				   	});	
		   	});
	 }
};
