
// config vars
var confirm_delete_message='Sigurno želite obrisati fotografiju?';
//

function deleteauction(id) {
	if (confirm("Sigurno želite obrisati aukciju?")) {
		window.location="auction.php?section=active&delete="+id;
	}
}


function implode (glue, pieces) {
    // Joins array elements placing glue string between items and return one string  
    // 
    // version: 911.718
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}


			
function ajaxFileUpload(element,successFunction,onComplete,about) {
		var about=about || 0;
		var element=element,successFunction=successFunction,onComplete=onComplete;
		
		$(element).parent().css({position:'relative'});
		
		
		$progress=$('<div>')
			.css({
				display:'none',
				position:'absolute',
				padding:'3px',
				width:'300px',
				
				background:'white',
				border:'1px solid #aaaaaa'
				
			})
			.append(
				$('<table>')
					.append(
						$('<tr>')
							.append(
								$('<td>')
									.append($('<img>').attr('src','images/loader.gif'))
							)
							.append(
								$('<td>')
									.append($('<span>').html('Fotografija se šalje...'))
							)
					)
			)
		$progress.insertBefore($(element));
		
		
		$($progress)
		.ajaxStart(function(){
			$(this).slideDown(500);
		})
		.ajaxComplete(function(){
			$(this).slideUp(500,function() {$(this).hide(); onComplete();});
		});

		$.ajaxFileUpload
		(
			{
				url:'ajaxfileupload/doajaxfileupload.php?about='+about+'&sid='+$("#sid").val(),
				secureuri:false,
				fileElementId:$(element).attr("name"),
				dataType: 'json',
				success: function (data, status)
				{
					if(typeof(data.error) != 'undefined')
					{
						if(data.error != '') {
							alert(data.error);
							//console.log(data);
						} else {
							if (successFunction) successFunction(data.msg);
						}
					}
				},
				error: function (data, status, e)
				{
					//console.log(data);
					alert(data);
				}
			}
		)
		
		return false;

	}
	
//var some=1; function cpp() {console.log(some++);}

//alert(-1);
$(document).ready(function(){ 
	//alert(0);
	
	
	// inline price editing
	$(".price_field.editable").click(function(){
		var $span = $(this);
		var $t = $("<input type='text' name='edit-price' />");
		$t.val($span.html());
		
		var editcomplete = function($t) {
			$.post("inlineedit.php",{action:'update_article_startprice',id:$span.attr("id"),price:$t.val()},function(response) {
				if (response.result == true) {
					$span.html(response.price);
					$t.blur();
				} else {
					alert(response.message);
					$t.select();
				}
			},'json');
			
			return false;
		}
		
		$t.keydown(function(e){
			switch (e.keyCode) {
				case 13:
					editcomplete($(this));
					return false;
				break;
				case 27:
					$(this).blur();
					return false;
				break;
				case 9:
					// implement a tab functionality
				break;
				
			}
			
			
			
			
		});
		
		$t.blur(function(){
			$(this).hide();
			$span.css({opacity:1,color:'#00AA00',backroundColor:'yellow'}).show().animate({opacity:1,color:'#C65400'},1800);
		});
		
		$t.prependTo($span.parent());
		$t.width($span.width());
		$t.height($span.height());
		$t.select();
		$span.hide();
	});
	
	
			
	$("body").prepend($("<div class='overlay'>").overlay({
		useCurtain:false,
		opacity:0.4,
		animDuration:100
	}));
	
	$(".overlay").hide().append($("<div class='html'>")).append($("<input type='button' value='Zatvori'>").click(function(){
		$(".overlay").overlay("hide");
	}));
	
	// reserved price
	$("img[src*=reserved.png], img[src*=notreserved.png]").add().css({cursor:'pointer'}).click(function(){
		$.post("gettext.php",{variable:'reserved_price'},function(html){
			$(".overlay .html").html(html);
			$(".overlay").overlay("show");
		});
	});
	
	

	
// TIMERS :: Put current microtime into id, and the enddate into title of an object classed 'countdown'
	if ($('.countdown').length>0) {
		$('.countdown').each(function(i) {
			var dt = new Date();  
			dt.setTime($(this).attr('id'));
			var enddate=new Date();
			enddate.setTime($(this).attr('title'));
			$(this).attr("title","");
			$(this).countdown({
				serverSync:function() {return dt;},
				until: enddate,
				layout:'<span><strong>{dn}</strong>d <strong>{hn}</strong>h</span> <span><strong>{mn}</strong>min</span> <span style=\'display:none\'><strong>{snn}</strong> s</span>',
				onTick:function(periods) {
					if (periods[3]==0 && periods[4]==0) {
						if (periods[5]<3) {
							$(this).find('span,strong').css({'color':'red'});
							$(this).find('span:eq(0)').css({display:'none'});
							$(this).find('span:eq(2)').css({display:'inline'});
							if (periods[5]==0) $(this).find('span:eq(1)').css({display:'none'});
						}
					}
				},
				onExpiry: function() {
					$(".bid").html("<br /><h3>Aukcija je završena!</h3>");
					$(this).html('<strong>Aukcija završena!</strong>')
					$(this).parent().parent().addClass('expired');
				},
				tickInterval:1
			});
		});
	}
	//alert(2);

	
	/*
	// Search autocomplete
	var default_search_text="(Tražilica)";
	$("#search_input")
	.focus(function () {
		$(this).addClass('active');
		if ($(this).val()==default_search_text) $(this).val("");
	})
	.blur(function () {		
		$(this).removeClass('active');
		if ($(this).val()!=default_search_text && $(this).val()=='') $(this).val(default_search_text);
	})
	.autocomplete(
		"autocomplete.php",
		{selectFirst:false,
		delay:200,
		width:400,
		onItemSelect:function() {
			$("#search_form").submit();
		}
		}
	);
	*/

 //alert(3);
	
	// ping for updates of status
	var ping=function() {
		$.get("modules/stats/stats.php",{action:'ping'},function(data) {
			if (data) {
				try {
					for (item in data) {
						if ($("#stats_"+item).length>0 && item!='users') {
							$("#stats_"+item).html(data[item]);
							
						}
					}
				} catch (e){}
				
				var users=data.users,title='';
				if (users && users.length>0) {
					for (i in users) title+=(users[i].username+" ");
				} 
				$("#stats_onlinecount").attr("title",title);
			} 
			setTimeout(ping,120000);
		},'json');
	}
	ping();
	
	//alert(4);

	// HANDLE THE FCK EDITOR FOR TEXTAREAs
	var FCK_instances = [];
	if ($('textarea.fck').length>0) {
		var fck_index = 1;
		$('textarea.fck').each(function(){
			$(this).fck({
				name:$(this).attr("name"),
				instance:$(this).attr("name"),
				instanceName:$(this).attr("name"),
				path: 'cms/fckeditor/',
				height:'240px',
				toolbar: 'Basic'
			})
			
			 FCK_instances[$(this).attr("name")] = 'fck'+fck_index;
			 fck_index++;
		}); 
	}
	


	// the zoom image effect
	if ($("a.zoomable").length>0) { 
		$("a.zoomable").zoomimage({
			border:5,
			centered:true,
			caption:false,
			controls:false
		});
		
	}
	
	if ($("a.zoomable_list").length>0) {
		try {
			$("a.zoomable_list").zoomimage({
				border:5,
				centered:true,
				caption:false,
				opacity:0.6,
				controls:false
			});
		} catch(e) {alert (e)}
	}
	


	// OFFERS and expander:
	if ($('#offerlist').length>0) {
		$('#offerlist').hide();
		var offer_list_state=false;
		$('#offer_expander').click(function () {
			if (!offer_list_state) {
				$('#offerlist').show();
				$('#offer_expander').removeClass('expander').addClass('contractor');
			} else {
				$('#offerlist').hide();
				$('#offer_expander').removeClass('contractor').addClass('expander');
			}
			offer_list_state=!offer_list_state;
		})
		
		$('#offernum').click(function() {
			$('#offerlist').show();
			$('#offer_expander').removeClass('expander').addClass('contractor');
			offer_list_state=true;
			$.scrollTo('#offerlist',300);
		});
	}
	
	// GRADES and expander:
	if ($('#gradelist').length>0) {
		$('#gradelist').hide();
		var grade_list_state=false;
		$('#grade_expander').click(function () {
			if (!grade_list_state) {
				$('#gradelist').show();
				$('#grade_expander').removeClass('expander').addClass('contractor');
			} else {
				$('#gradelist').hide();
				$('#grade_expander').removeClass('contractor').addClass('expander');
			}
			grade_list_state=!grade_list_state;
		})		
	}
	


	//alert(7);
	
	// suggest new category
	if ($('#suggest_new_category').length>0) {
		
		$('#suggest_new_category').click(function() {
				$('#suggest_form').slideDown(300,function(){
					$(this).show();
					$('#suggest_form [name=newcategory]').select();
				});
		});
		
		$('#suggest_submit').click(function() {
			var suggestion=$('#suggest_form [name=newcategory]').val();
			$.get('suggest.php',{newcategory:suggestion},function(data) {
				if (data!='null') {
					$('#suggest_form').slideUp(300,function(){
						$(this).hide();
						$('<p class="success">Hvala na Vašem prijedlogu!</p>').insertAfter($('#suggest_new_category').hide()).hide().fadeIn(300);
					});
				} else {
					$('#suggest_form').slideUp(300,function(){
						$(this).hide();
						$('<p class="error">Prijedlog odbijen!</p>').insertAfter($('#suggest_new_category').hide());
					});
				}
			});
		});
		
		$('#suggest_cancel').click(function() {
			$('#suggest_form').slideUp(300,function(){$(this).hide();});
		});
	}

	//alert(8);

	
	// leave comment
	if ($('#leave_comment').length>0) { 
		comment_state=false;
		$('#leave_comment').click(function () {
			if (!comment_state) {
				$('#comments_form').show(1,function() {
					$(this).find("textarea").select();
				});
			} else {
				$('#comments_form').slideUp(300);
			
			}
			comment_state=!comment_state;			
		});
	}
	
	//alert(9);


	// PAGINATION: CHOOSE CUSTOM LIMIT
	if ($("select[name=limit]").length>0) {
		$("select[name=limit]").change(function() {
			var script=$(this).parent().attr("name");
			document.location=script+$(this).val();
		})
	}
	
	
	// TRACK articles
	if ($("#track_article_checkbox").length>0) {
		$("#track_article_checkbox").click(function() {
			var value=$(this).val();
			var chk=$(this).attr("checked");
			$.get(
				"ajax_track_article.php",
				{'data':value+','+((chk) ? '1' : '0')},
				function (data){
					message = (chk) ? "Predmet je dodan na Vaš popis." : "Predmet je izbrisan s Vašeg popisa.";
					var $msg=$('<div>').addClass('success').html(message).css({'position':'absolute','padding':'6px'});
					$msg.insertAfter($('.track_article:first'));
					$msg.hide().fadeIn(300);
					setTimeout(function () {$msg.fadeOut(500,function() {$(this).remove();})},1500);
				
				}
			);			
		});
	}
	
	
	// GRADE USERS
	/*
	if ($("a.grade").length>0) {
	
		var hidegradeform=function() {
				$("#grade_form").slideUp(300);
				$(".activecell").removeClass("activecell");
		}
		
		var showgradeform=function(obj) {
			$(".activecell").removeClass("activecell");
			$(obj).parent().parent().find("td").addClass("activecell");
			

			$(document).keyup(function(e) {
				if (e.keyCode==27) hidegradeform();
			});
						
			t=$(obj).parent().offset();
			th=$(obj).parent().height();
			fw=$("#grade_form").width();
			$("#grade_form").css({'position':'absolute',left:t.left-fw+90,'top':t.top+30,'z-index':'100'}).show();

			$("#grade_form").hide().slideDown(300,function() {
				$("#grade_form textarea").val("").focus();
			});
		}
		
		
		$("#grade_cancel").click(function() {
			hidegradeform();
		});
	
		$("a.grade").click(function() {
			var grade;
			sign=$(this).attr("id").substring(0,1);
			switch(sign) {
				case "+": grade=1; $("#grade_positive").click().attr("checked",true); break;
				case "0": grade=0; $("#grade_neutral").click().attr("checked",true); break;
				case "-": grade=-1; $("#grade_negative").click().attr("checked",true); break;
			}
			
			$id_article=$(this).attr("id").substring(1,10)
						
			$("#grade_id_article").val($id_article);
			
			showgradeform(this);
			
		});
		
		$("#set_grade_button").click(function() {
			var grade,id_article,comment;
			
			if ($("#grade_positive").attr("checked")==true) grade=1;
			if ($("#grade_neutral").attr("checked")==true) grade=0;
			if ($("#grade_negative").attr("checked")==true) grade=-1;
			
			id_article=$("#grade_id_article").val();
			comment=$("#grade_comment").val();
			
			
			$.get("modules/users/setgrade.php",{action:'setgrade',id_article:id_article,grade:grade,comment:comment},function(data){
				var $msg,data=data;
				if (data['error']==false) {
					
					hidegradeform();
					var xparent=$("a.grade[id=-"+$id_article+"]").parent();
					xparent.html("");
					
					xparent.html(data['success']);
					xparent.find("img").hide().fadeIn(200);
					// update the status in the left sidebar :: menu
					$("#grades_status").html($("#grades_status").html()-1);
					
					setTimeout(function() {
						
						var tbody=xparent.parent().parent();
						var row=xparent.parent();
						row.fadeOut(500,function() {
							$(this).remove();
							tbody.find("tr:odd").removeClass('row0').addClass('row1');
							tbody.find("tr:even").removeClass('row1').addClass('row0');
						});
						
					},500);
					
				} else {
					hidegradeform();
					alert(data['error']);
				}
			},'json');
		});
	}
	*/
	
	// select all auction on page checkbox
	if ($(".select_all").length) {
		$(".select_all").click(function() {
			var prefix="";
			if ($(this).val().length>1) prefix="#"+$(this).val()+" ";
			//console.log(prefix);
			$(prefix+"input[type=checkbox].article_select").attr("checked",$(this).attr("checked"));
		});
	}
	
	
	if ($("#select_all").length) {
		$("#select_all").click(function() {
			$("input[type=checkbox].article_select").attr("checked",$(this).attr("checked"));
		});
	}
	
	// calculate cost for repeating auction
	if ($(".restart_fee").length) {
		
		var calculateCost=function() {
			var total=0;
			$(".restart_fee").each(function() {
				if ($(this).attr("checked")) {
					total+=$(this).val()*1;
				}
			});
			total=total.toFixed(2)+'';
			total=total.replace(".",",");
			$("#total_cost").html(total+' kn');
		}
	
		$(".restart_fee").click(calculateCost);
	}
	
	if ($("#charge_all_fees").length) {
		$("#charge_all_fees").click(function() {
			$("input[type=checkbox]..restart_fee").attr("checked",$(this).attr("checked"));
			calculateCost();
		});
	}
	
	if ($("#buynowbutton").length) {
		$("#buynowbutton").click(function(e){
			var c=confirm("Sigurno želite odmah kupiti ovaj predmet?");
			if (!c) return false;
		});
	}
	
	
	var controlKeyDown=false;
	// affiliate link input behaviour
	$('.affiliatelink').focus(function() {
		
	}).mousedown(function() {
		$(this).select();
		return false;
	}).keydown(function(e){
		if (e.keyCode==17) controlKeyDown=true;
		if ((e.keyCode==67 || e.keyCode==88) && controlKeyDown) return true;
		return false;
	}).keyup(function(e){
		if (e.keyCode==17) controlKeyDown=false;
	}).change(function(){
		return false;
	});
	
	
	// saleterm handling on adding auction (applies to prouduced in modules/auctions/add.php)
	function setEditorValue( instanceName, text ) {
	    
		
		// Get the editor instance that we want to interact with.
	    var oEditor = FCKeditorAPI.GetInstance( FCK_instances[instanceName] ) ;
		
	    // Set the editor contents.
	    oEditor.SetHTML( text ) ;
	}
	
	//console.log("jquery layer applied");
	
	
	// hide technical ::  21:15 25.1.2011.
	var cookie_val = 1;
	$.post("getcookie.php",{cookie:'technical'},function(val) {
		try {
			if (typeof val == "undefined" || !val) {
				$(".technical_text").slideDown(500);
			}
		} catch (e) {
		
		}
		cookie_val = val;
	});
	
	$("#hidethis").click(function() {
		cookie_val = 1-cookie_val;
		if (!cookie_val) {
			$(".technical_text").slideUp(300);
		} else {
			$(".technical_text").slideDown(300);
		}
		$.post("setcookie.php",{cookie:'technical',value:cookie_val,time:1000000},function(x) {
			
		});
		
		
		
	});

	
	
});		

