function getSecondsFromTime()
  {
	var d = new Date(); 
	var secondsFromTime = Math.round(d.getTime()/1000);
	return secondsFromTime;
  }

function cutString(string,cutAt,cutFrom)
  {
	if (string.length > cutAt) var newString = string.substr(cutFrom,cutAt) + '...';
	else var newString = string;
	return newString;
  }

function adjustDialogPosition(dialog)
  {
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();
	var dialogWidth = $(dialog).outerWidth(true);
	var dialogHeight = $(dialog).outerHeight(true);
	var top = Math.floor((windowHeight-dialogHeight)/2); if(top < 0) top = 0;
	var left = Math.floor((windowWidth-dialogWidth)/2); if(left < 0) left = 0;
	$(dialog).css({'left':left+'px','top':top+'px'});
  }

function formatBytes(byteSize)
  {
	var byteSize = Math.round(byteSize / 1024 * 100) * .01;
	var suffix = 'KB';
	if (byteSize > 1000) {
		byteSize = Math.round(byteSize *.001 * 100) * .01;
		suffix = 'MB';
	}
	var sizeParts = byteSize.toString().split('.');
	if (sizeParts.length > 1) {
		byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2);
	} else {
		byteSize = sizeParts[0];
	}
	var returnVar = new Array();
	returnVar[0] = (byteSize == 0 ? 0.1:byteSize);
	returnVar[1] = suffix;
	return returnVar;
  }

function openUploadDialog(item_id)
  {
	$('#dialog').addClass('hidden');
	$('#queueMessage').show();
	$('#fileInput').uploadifySettings('hideButton',false);
	$('#fileInput').uploadifySettings('wmode','opaque');
	$('#uploadFor').html($('#orderedItemId-'+item_id).attr('title')).attr('title',item_id);
	$('#dialog-bg').removeClass('hidden zIndexMin').addClass('zIndexMax');
	$('#orderedItemId-'+item_id).find('.deleteTarget').each(function(){
									var queueID = $(this).find('.deleteUploadedFile').attr('title');
									var filename = $(this).find('.filename').html();
									var filesize = $(this).find('.filesize').html();
									var filesizeFormated = formatBytes(parseInt(filesize));
									$('#fileInputUploader').before('<div id="'+queueID+'" class="uploadingQueue-item uploaded deleteTarget"><img class="deleteUploadedFile" title="'+queueID+'" src="/scripts/uploadify-210/cancel.png" alt="'+item_id+'" /><span class="filename" title="'+filename+'">'+filename+'</span><span class="filesize" title="'+filesize+'"> | '+filesizeFormated[0]+filesizeFormated[1]+' |</span><span class="infoStatus"></span></div>');
									});
	adjustDialogPosition('#dialog');
	$('#dialog').removeClass('hidden');
	
  }

function closeUploadDialog()
  {
	var item_id = $('#uploadFor').attr('title');
	
	$('#fileInput').uploadifySettings('hideButton',true);
	$('#fileInput').uploadifySettings('wmode','transparent');
	$('#dialog-bg').removeClass('zIndexMax').addClass('hidden zIndexMin');
	$('#queueMessage').nextAll('.uploaded').removeClass('uploaded');
	$('.uploadingQueue-item').find('.infoStatus').html('');
	$('#uploadFor').html('').attr('title','');
	$('#uploadingInfo').hide();

	if($('.uploadingQueue-item').length != 0) //UKOLIKO IMA BAR 1 UPLOADOVAN FAJL
	  {
		$('#orderedItemId-'+item_id).find('.uploadedFilesInfo').empty();
		if($('#orderedItemId-'+item_id).find('.filesTitle').is(':hidden')) $('#orderedItemId-'+item_id).find('.filesTitle').show();
		$('.uploadingQueue-item').each(function(){
							var filename = $(this).find('.filename').html();
							var filesize = $(this).find('.filesize').attr('title');
							var queueID = $(this).attr('id');
							$('#orderedItemId-'+item_id).find('.uploadedFilesInfo').append('<div class="deleteTarget"><img class="deleteUploadedFile" title="'+queueID+'" src="/scripts/uploadify-210/cancel.png" alt="'+item_id+'" /><span class="filename">'+filename+'</span><span class="filesize hidden">'+filesize+'</span></div>');
							});
	  }
	else
	  {
		$('#orderedItemId-'+item_id).find('.uploadedFilesInfo').empty();
		$('#orderedItemId-'+item_id).find('.filesTitle').hide();
	  }
	$('.uploadingQueue-item').remove();
  }

function azurirajNarudzbenicu()
  {
	var temp_cena = 0; var temp_kolicina = 0; var thisKolicina_value = 0;
	if($(".orderedItemTable").length > 0)
	  {
		$(".orderedItemTable").each(function(){
					temp_cena = temp_cena + parseInt($(this).find(".cenaKristala").attr('title'));
					thisKolicina_value = parseInt($(this).find(".orderedItem-amountInput").val()); if(isNaN(thisKolicina_value)) thisKolicina_value = 0;
					temp_kolicina = temp_kolicina + thisKolicina_value;
						});
		
	  }
	else
	  {
		temp_cena = 0; temp_kolicina = 0;
		$("#narudzbenica-spisak-infoMessage-empty").hide();
		$("#shoppingCart-actions").addClass('displayNone');
	  }
	
	var patternn = /(^1$)|(^[0-9]*[023456789]1$)/;
	$("#narudzbenica-ukupanBrKristala-info").html(temp_kolicina);
	if(String(temp_kolicina).match(patternn) == null)
		$("#narudzbenica-ukupanBrKristala-info-slovoA").html("a");
	else
		$("#narudzbenica-ukupanBrKristala-info-slovoA").html("");
	if(temp_kolicina == 0)
	  {
		$("#narudzbenica-info-jestePrazna").show();
		$("#narudzbenica-info-nijePrazna").hide();
	  }
	else
	  {
		$("#narudzbenica-info-nijePrazna").show();
		$("#narudzbenica-info-jestePrazna").hide();
	  }
  }

function addToOrDeleteFromCart(to_do, photo_id, amount, $deleteObject)
 {
	$.ajax({
	url:URL_TO_THIS_SCRIPT+"/cart.php",
	type: "POST",
	cache: false,
	data: {
		action: to_do,
		crystal_amount: amount,
		crystal_photoID: photo_id,
		visitorCookie_id: visitor_id,
		orderID: order_id
		},
	dataType: "html",
	success: function(data){
							if(data != '')
								 alert(data);
							else if(to_do == 'add_to_cart')
							  {
								var temp_brKristala = parseInt($('#narudzbenica-ukupanBrKristala-info').html());
								$('#narudzbenica-ukupanBrKristala-info').html(temp_brKristala+parseInt(amount));
								if($('#narudzbenica-info-nijePrazna').css('display') == 'none')
								  {
									$('#narudzbenica-info-nijePrazna').show();
									$('#narudzbenica-info-jestePrazna').hide();
								  }
								//alert("Kristal je uspešno dodat u narudžbenicu.");
								window.open(URL_TO_THIS_SCRIPT+'/korpa/','_self');
							  }
							else if(to_do == 'remove_from_cart')
							  {
								$deleteObject.remove();
								azurirajNarudzbenicu();
								alert("Kristal je uspešno obrisan iz narudžbenice.");
							  }
						  }
	});
 }

function subscribe(to_do, email_value)
 {
	$.ajax({
	url:URL_TO_THIS_SCRIPT+"/includes/subscribe.php",
	type: "POST",
	cache: false,
	data: {
		action: to_do,
		email: email_value,
		orderID: order_id,
		visitorCookie_id: visitor_id
		},
	dataType: "html",
	success: function(data){
							if(data == 'ok' && to_do == "add-me")
							  {
								$('#subscribe-input').attr('title',$('#subscribe-input').val());
								$("#subscribe-link").toggleClass('button disabledButton');
								if($("#unsubscribe-link").hasClass('disabledButton')) $("#unsubscribe-link").toggleClass('button disabledButton');
								alert("Vaša email adresa je uspešno sačuvana.\n\nPodsećamo Vas još jednom da je Vaša e-mail adresa sigurna kod nas. Obavezujemo se da je nećemo prosleđivati trećim licima poštujući privatnost Vaših podataka");
							  }
							else if(data == 'ok' && to_do == "remove-me")
							  {
								$('#subscribe-input').attr('title','').val($("#subscribe-input").parent().attr('title'));
								if($("#subscribe-link").hasClass('button')) $("#subscribe-link").toggleClass('button disabledButton');
								$("#unsubscribe-link").toggleClass('button disabledButton');
								alert("Vaša email adresa je uspešno uklonjena.\n\nPodsećamo Vas još jednom da je Vaša e-mail adresa bila sigurna kod nas. Održali smo obećanje da je nećemo prosleđivati trećim licima poštujući privatnost Vaših podataka");
							  }
							else if(data != '')
							  {
								alert(data);
							  }
						  }
	});
 }

function deleteUploadedFile(object, itemID, queueID, filename)
 {
	$.ajax({
	url:URL_TO_THIS_SCRIPT+"/cart.php",
	type: "POST",
	cache: false,
	data: {
		action: 'delete_uploaded_file',
		visitorCookie_id: visitor_id,
		orderID: order_id,
		item_id: itemID,
		queue_id: queueID,
		file_name: filename,
		folder: upload_dir+'/'+visitor_id+'/'+order_id+'/'+itemID
		},
	dataType: "html",
	success: function(data){
							if(data == '')
							  {
								if(object.closest('.uploadedFilesInfo').find('.deleteTarget').length > 1)
								  {
									object.closest('.deleteTarget').remove();
								  }
								else if(object.closest('.uploadedFilesInfo').find('.deleteTarget').length == 1)
								  {
									object.closest('.orderedItem-filesContent').find('.filesTitle').hide();
									$('#queueMessage').show();
									object.closest('.deleteTarget').remove();
								  }
							  }
							else alert(data);
						  }
	});
 }

function completeOrder()
 {
	$.ajax({
	url:URL_TO_THIS_SCRIPT+"/cart.php",
	type: "POST",
	cache: false,
	data: {
		action: 'complete_order',
		visitorCookie_id: visitor_id,
		orderID: order_id,
		is_company: $('#company_name').is(':visible') ? 1:0,
		pib: $('#pib').val(),
		name: $('#name').val(),
		company_name: $('#company_name').val(),
		email: $('#email').val(),
		phone: $('#phone').val(),
		fax: $('#fax').val(),
		address: $('#address').val(),
		city: $('#city').val(),
		postal_code: $('#postalCode').val(),
		note: $('#note').val()
		},
	dataType: "html",
	success: function(data){
							if(data == '')
							  {
								//$('#orderCompleted').show().siblings('div').hide();
								//$('#completeOrderDiv, .orderedItemTable').hide();
								window.location.href = URL_TO_THIS_SCRIPT + "/hvalaNaPorudzbini";
							  }/*
							else if(data.indexOf("_RETURN-VALUE|") != -1)
							  {
								var begin_split = data.indexOf("E|")+2;
								var end_split = data.lastIndexOf("|R")-2;
								var new_order_value = data.slice(begin_split,end_split);
								$.cookie('order_id', new_order_value);
							  }*/
							else alert(data);
						  }
	});
 }

function contactUs()
 {
	$.ajax({
	url:URL_TO_THIS_SCRIPT+"/cart.php",
	type: "POST",
	cache: false,
	data: {
		action: 'contact_us',
		visitorCookie_id: visitor_id,
		name: $('#name_value').val(),
		email: $('#email_value').val(),
		subject: $('#subject_value').val(),
		message: $('#message_value').val()
		},
	dataType: "html",
	success: function(data){
							if(data == '')
							  {
								$(".infoBox-contactUs").show();
								$('#div-contentTopRight_kontaktForma input, #div-contentTopRight_kontaktForma textarea').val('');
								$("#button-contactForm_sendMessage").toggleClass('disabledButton button');
							  }
							else 
							  {
								$("#button-contactForm_sendMessage").toggleClass('disabledButton button');
								alert(data);
							  }
						  }
	});
 }

function init()
  {
	//
	if(is_ie6 == true) alert('Koristite zastarelu verziju pretraživača(Internet Explorera) pa samim tim naš veb sajt nije u stanju da Vam ispravno prikaže naše proizvode. Molimo Vas da što pre izvršite ažuriranje na novu verziju Internet Explorer pretraživača ili da instalira drugi pretraživač(Opera, Google Chrome ili Mozilla Firefox).');
	
	$('#bela-pozadina').click(function(){
			$('#nd-mainContent').css('background','white');
			$('.box-tbody').css('background-image','url(\'themes/bg.jpg\') !important');
			$('.thumbFrame').css('background-image','url(\'themes/bg.jpg\') !important');
			});
	$('#svetloplava-pozadina').click(function(){
			$('#nd-mainContent').css('background','skyblue');
			$('.box-tbody').css('background-image','url(\'themes/bg.jpg\') !important');
			$('.thumbFrame').css('background-image','url(\'themes/bg.jpg\') !important');
			});
	//
  
	//UBACIVANJE FLASHA NA POCETNU STRANICU KAKO BI POSTIGAO EFEKAT AUTOMATSKOG AKTIVIRANJA FLASHA
	$('.flashContentToBeAdded').each(function(){
			var ID = $(this).attr('id'); 
			var filename = ID.slice((ID.indexOf("-"))+1);
			var html = "<object type=\"application/x-shockwave-flash\" data=\"../files/"+filename+".swf\" width=\"300\" height=\"120\">\
							<param name=\"movie\" value=\"../files/"+filename+".swf\" />\
							<param name=\"wmode\" value=\"transparent\">\
						</object>";
			$(this).html(html);
			});
	//UBACIVANJE FLASHA NA POCETNU STRANICU KAKO BI POSTIGAO EFEKAT AUTOMATSKOG AKTIVIRANJA FLASHA
  
  
  /* L I S T A   K R I S T A L A */
	var $subscribe = $("#subscribe-link");
	var $unsubscribe = $("#unsubscribe-link");
	
	$('#slideshowHolder').jqFancyTransitions({
									effect: '', // wave, zipper, curtain
									width: 160, // width of panel
									height: 125, // height of panel
									strips: 20, // number of strips
									delay: 2500, // delay between images in ms
									stripDelay: 50, // delay beetwen strips in ms
									titleOpacity: 1, // opacity of title
									titleSpeed: 0, // speed of title appereance in ms
									position: 'alternate', // top, bottom, alternate, curtain
									direction: 'fountainAlternate', // left, right, alternate, random, fountain, fountainAlternate
									navigation: false, // prev and next navigation buttons
									links: false // show images as links});
											});
	
	// CLICK EVENT AND HOVER EFFECTS ON HEADER BUTTONS
	$(".nd-header-buttons p, .nd-header-buttons table").hover(function() {
									if(!$(this).hasClass('noHoverEffect')) $(this).addClass('backgroundPosition-bottomMiddle'); 
									var href = $(this).find('.nd-header-buttons-link').attr('href');
									if(href != null) $(this).addClass('cursorPointer'); 
								}, function() {
									$(this).removeClass('backgroundPosition-bottomMiddle cursorPointer');
								})
						  .click(function(){
									var href = $(this).find('.nd-header-buttons-link').attr('href');
									if(href != null) window.open(href,'_self');
									
								});
	// CLICK EVENT AND HOVER EFFECTS ON HEADER BUTTONS
	
	// ADD TO CART ACTION AND HOVER EFFECTS ON "DODAJ U KORPU" BUTTON
	$(".button-addToCart").hover(function() {
								$(this).toggleClass('button-addToCart-over'); 
								})
						  .click(function(){
								/*var kolicina = prompt("Unesite količinu za odabrani artikal:\n\n"+$(this).attr("title"),"1");
								var ID = this.id; var ID_of_photo = ID.slice((ID.lastIndexOf("-"))+1);
								
								if(!isNaN(parseInt(kolicina)) && parseInt(kolicina) > 0 && parseInt(kolicina) < 10000)
								  {
									addToOrDeleteFromCart("add_to_cart",ID_of_photo,kolicina,false);
								  }
								else if(kolicina != null)
								  alert('Pogrešan unos!!! Molimo Vas da unesete količinu koja je u rasponu od 1 do 10000 komada.');
								else return false;*/
								if($(this).hasClass('clicked')) return false;
								var ID = this.id; var ID_of_photo = ID.slice((ID.lastIndexOf("-"))+1);
								$(this).addClass('clicked');
								addToOrDeleteFromCart("add_to_cart",ID_of_photo,1,false);
								});
	// ADD TO CART ACTION AND HOVER EFFECTS ON "DODAJ U KORPU" BUTTON
	
	// ORDER BUTTON
	$("#orderItems-button").click(function(){
							/*if($('.orderedItem-saveChanges').filter('.button').length > 0)
							  {
								var provera = confirm('Napravili ste izmene u korpi!\n\nDa li zaista želite da potvrdite narudžbinu bez izmena koje ste napravili?');
								if(!provera) return false;
							  }
							else if($('.inputError').length > 0)
							  {
								$('.inputError, .inputError input').addClass('inputErrorMark');
								var provera = alert('Postoji greška u popunjavanju gornjih polja. Molimo Vas da obratite pažnju na delove uokvirene crvenom bojom i da ispravite eventualne greške pre nego što opet pokušate da kompletirate narudžbenicu.');
								return false;
							  }*/
							if($('.inputError').length > 0)
							  {
								$('input.inputError, .inputError input').addClass('inputErrorMark');
								var provera = alert('Postoji greška u popunjavanju gornjih polja. Molimo Vas da obratite pažnju na delove uokvirene crvenom bojom i da ispravite eventualne greške pre nego što opet pokušate da kompletirate narudžbenicu.');
								return false;
							  }
							else
							  {
								if($('.orderedItem-saveChanges').filter('.button').length > 0)
									$('.orderedItem-saveChanges').filter('.button').each(function(){ $(this).click(); });
								window.open($(this).attr('title'),'_self');
							  }
							});
	// ORDER BUTTON
	
	// COMPLETE ORDER
	$("#completeOrderButton").click(function(){
							if($('#completeOrderDiv input').filter(function(index) { return ($(this).val() == '' && $(this).is(':visible') && !$(this).hasClass('optional')); }).length > 0)
							  {
								alert('Sva polja označena sa zvezdicom morate obavezno popuniti da biste mogli poslati porudžbinu!');
								return false;
							  }
							$(this).toggleClass('disabledButton button');
							completeOrder();
							$('#narudzbenica-info-jestePrazna').show();
							$('#narudzbenica-info-nijePrazna').hide();
							$('#narudzbenica-ukupanBrKristala-info').html('0');
							$(this).toggleClass('disabledButton button');
							});
	// COMPLETE ORDER
	
	// CONTACT US SUBMIT MESSAGE
	$("#button-contactForm_sendMessage").click(function(){
							$(".infoBox-contactUs").hide();
							if($('#div-contentTopRight_kontaktForma input, #div-contentTopRight_kontaktForma textarea').filter(function(index) { return ($(this).val() == '' && $(this).is(':visible') && !$(this).hasClass('optional')); }).length > 0)
							  {
								alert('Sva polja označena sa zvezdicom morate obavezno popuniti da biste mogli poslati poruku!');
								return false;
							  }
							$(this).toggleClass('disabledButton button');
							contactUs();
							});
	// CONTACT US SUBMIT MESSAGE
	
	// HOVER EFFECTS ON GALLERY THUMB PICTURES
	$(".catsThumbFrame-out").hover(function() { 
										$(this).addClass('catsThumbFrame-in');
								   },
								   function() { 
										$(this).removeClass('catsThumbFrame-in'); 
								   })
							.click(function() { 
										$(this).removeClass('catsThumbFrame-in');
								   });
	
	$(".catsThumbLink").hover(function() { 
								$(this).prev('.catsThumbFrame-out').addClass('catsThumbFrame-in'); 
							  },
							  function() { 
								$(this).prev('.catsThumbFrame-out').removeClass('catsThumbFrame-in');
							  })
					   .click(function() { 
								$(this).prev('.catsThumbFrame-out').removeClass('catsThumbFrame-in');
							  });
	
	$(".itemThumbPhoto-out").hover(function() { 
										$(this).addClass('itemThumbPhoto-in'); 
								   },
								   function() { 
										$(this).removeClass('itemThumbPhoto-in'); 
								   });
	// HOVER EFFECTS ON GALLERY THUMB PICTURES
/* L I S T A   K R I S T A L A */
	
/* K O R P A */
	
	// COMPLETE ORDER RADIO
	$(".customerType").change(function(){
							$('.input-person').each(function(){$(this).toggleClass('displayNone');});
							$('.input-companies').each(function(){$(this).toggleClass('displayNone');});
							});
	// COMPLETE ORDER RADIO
	
	//SAVE CHANGES
	$(".orderedItem-saveChanges").click(function(){
							if($(this).hasClass('disabledButton')) return false;
							
							var $this = $(this);
							var $this_table = $this.closest('.orderedItemTable');
							
							$this.removeClass('button').addClass('disabledButton'); //ONEMOGUCI VISE KLIKOVA ODJEDNOM
							$this_table.find('input.inputOrTextarea-focusOut').attr('disabled','disabled'); //ONEMOGUCI IZMENU INPUT POLJA DOK SE SACUVAVAJU IZMENE
							
							if($this_table.find('.input-personalisedText1').length == 0) { persText1 = ''; persText2 = ''; }
							else
							  {
								persText1 = $this_table.find('.input-personalisedText1').val();
								persText2 = $this_table.find('.input-personalisedText2').val();
							  }
							
							$.ajax({
								url:URL_TO_THIS_SCRIPT+"/cart.php",
								type: "POST",
								async: false,
								cache: false,
								data: {
										action: 'save_changes',
										visitorCookie_id: visitor_id,
										item_id: $this_table.find('.uploadButton').attr('title'),
										orderID: order_id,
										amount_value : $this_table.find('.orderedItem-amountInput').val(),
										numOfDesigns_value : $this_table.find('.orderedItem-designsInput').val(),
										personalisedText1_value : persText1,
										personalisedText2_value : persText2
									  },
								dataType: "html",
								success: function(data){
									if(data == 'ok')
									  {
										$this_table.find('.orderedItem-amountInput').attr('title',$this_table.find('.orderedItem-amountInput').val());
										$this_table.find('.orderedItem-designsInput').attr('title',$this_table.find('.orderedItem-designsInput').val());
										$this_table.find('.input-personalisedText1, .input-personalisedText2').each(function(){ $(this).attr('title',$(this).val()); });
										$this_table.find('.inputChanged').removeClass('inputChanged');
										azurirajNarudzbenicu();
										//alert('Izmene su uspešno sačuvane.');
									  }
									else
									  {
										$this.removeClass('disabledButton').addClass('button');
										alert('Izmene nisu uspešno sačuvane.\n\n'+data);
									  }
									$this_table.find('input.inputOrTextarea-focusOut').removeAttr('disabled');
								}
							});
						});
	//SAVE CHANGES
	
	//DELETE ITEM
	$("a.delete-shoppingItem").click(function(){
							var ID = this.id; var ID_of_photo = ID.slice((ID.lastIndexOf("-"))+1);
							var $this_table = $(this).closest('.orderedItemTable');
							var amount = parseInt($this_table.find('.orderedItem-amountInput').val());
							addToOrDeleteFromCart("remove_from_cart",ID_of_photo,amount,$this_table);
							azurirajNarudzbenicu();
							});
	//DELETE ITEM
	
	//INPUT PERSONALISED TEXT
	$(".input-personalisedText1, .input-personalisedText2").bind('keyup mouseleave', function(){
							var $this_table = $(this).closest('.orderedItemTable');
							var $statusDiv = $(this).closest('.personalise');
							var $save_changes = $this_table.find('.orderedItem-saveChanges');
							
							var firstRow_value = $this_table.find('.input-personalisedText1').val();
							var firstRow_startValue = $this_table.find('.input-personalisedText1').attr('title');
							var secondRow_value = $this_table.find('.input-personalisedText2').val();
							var secondRow_startValue = $this_table.find('.input-personalisedText2').attr('title');
							
							if(firstRow_value != firstRow_startValue || secondRow_value != secondRow_startValue)
							  {
								
								if(!$statusDiv.hasClass('inputChanged')) $statusDiv.addClass('inputChanged');
								
								if(firstRow_value == '' && secondRow_value == '')
								  {
									if($statusDiv.hasClass('inputError')) $statusDiv.removeClass('inputError');
									$statusDiv.find('input').each(function(){
											if($(this).hasClass('inputErrorMark')) $(this).removeClass('inputErrorMark');
											});
								  }
								else
								  {
									if(firstRow_value == '')
									  {
										if(!$statusDiv.hasClass('inputError')) $statusDiv.addClass('inputError');
									  }
									else
									  {
										if($statusDiv.hasClass('inputError')) $statusDiv.removeClass('inputError');
										$statusDiv.find('input').each(function(){
												if($(this).hasClass('inputErrorMark')) $(this).removeClass('inputErrorMark');
												});
									  }
								  }
							  }
							else
							  {
								if($statusDiv.hasClass('inputChanged')) $statusDiv.removeClass('inputChanged');
								if($statusDiv.hasClass('inputError')) $statusDiv.removeClass('inputError');
								$statusDiv.find('input').each(function(){
											if($(this).hasClass('inputErrorMark')) $(this).removeClass('inputErrorMark');
											});
							  }
							
							
							if(($this_table.find('.inputError').length == 0 && $this_table.find('.inputChanged').length > 0))
							  {
								if($save_changes.hasClass('disabledButton')) $save_changes.toggleClass('disabledButton button');
							  }
							else
							  {
								if($save_changes.hasClass('button')) $save_changes.toggleClass('disabledButton button');
							  }
							});
	//INPUT PERSONALISED TEXT
	
	//INPUT KOLICINA
	$(".orderedItem-amountInput, .orderedItem-designsInput").bind('keyup mouseleave', function(){
							var $this_table = $(this).closest('.orderedItemTable');
							var $save_changes = $this_table.find('.orderedItem-saveChanges');
							var $amountInput = $this_table.find('.orderedItem-amountInput');
							var $numOfDesignsInput = $this_table.find('.orderedItem-designsInput');
							//alert($amountInput.val().match(/^[1-9][0-9]*$/));
							if($numOfDesignsInput.length == 0)
							  {
								var numOfDesigns_value = 1;
								
								if($amountInput.val().match(/^[1-9][0-9]*$/) == null) 
								  {
									var amount_value = 0;
								  }
								else
								  {
									var amount_value = parseInt($amountInput.val());
								  }
							  }
							else
							  {
								if($amountInput.val().match(/^[1-9][0-9]*$/) == null || $numOfDesignsInput.val().match(/^[1-9][0-9]*$/) == null) 
								  {
									var amount_value = 0;
									var numOfDesigns_value = 1;
								  }
								else
								  {
									var amount_value = parseInt($amountInput.val());
									var numOfDesigns_value = parseInt($numOfDesignsInput.val());
									if(numOfDesigns_value > amount_value)
									  {
										numOfDesigns_value = 1;
										amount_value = 0;
									  }
								  }
							  }
							//alert(amount_value+'|'+numOfDesigns_value);
							var amount_startValue = parseInt($amountInput.attr('title')); if(isNaN(amount_startValue)) amount_startValue = 0;
							var numOfDesigns_startValue = parseInt($numOfDesignsInput.attr('title')); if(isNaN(numOfDesigns_startValue)) numOfDesigns_startValue = 0;
							var oneItemPrice = parseInt($this_table.find(".orderedItem-oneItemPrice").attr('title')); 
								if(isNaN(oneItemPrice))  oneItemPrice = 0;
							var preparationPrice = parseInt($this_table.find('.preparationPrice').attr('title')); 
								if(isNaN(preparationPrice) || amount_value == 0 || $this_table.find('.preparationPrice').length == 0)
									preparationPrice = 0;
							
							$this_table.find(".orderedItem-priceAndAmount").html(oneItemPrice*amount_value);
							$this_table.find(".preparationPrice-html").html(preparationPrice*numOfDesigns_value);
							$this_table.find(".orderedItem-priceAll").html(oneItemPrice*amount_value+preparationPrice*numOfDesigns_value).closest('.cenaKristala').attr('title',oneItemPrice*amount_value+preparationPrice*numOfDesigns_value);
							
							if(amount_value == 0 || ($numOfDesignsInput.length > 0 && numOfDesigns_value == 0))
							  {
								if(!$amountInput.hasClass('inputError')) $amountInput.addClass('inputError');
								if($amountInput.hasClass('inputChanged')) $amountInput.removeClass('inputChanged');
							  }
							else if(amount_value == amount_startValue && ($numOfDesignsInput.length == 0 || numOfDesigns_startValue == numOfDesigns_value))
							  {
								if($amountInput.hasClass('inputError')) $amountInput.removeClass('inputError');
								if($amountInput.hasClass('inputErrorMark')) $amountInput.removeClass('inputErrorMark');
								if($amountInput.hasClass('inputChanged')) $amountInput.removeClass('inputChanged');
							  }
							else
							  {
								if($amountInput.hasClass('inputError')) $amountInput.removeClass('inputError');
								if($amountInput.hasClass('inputErrorMark')) $amountInput.removeClass('inputErrorMark');
								if(!$amountInput.hasClass('inputChanged')) $amountInput.addClass('inputChanged');
							  }
							  
							if(($this_table.find('.inputError').length == 0 && $this_table.find('.inputChanged').length > 0))
							  {
								if($save_changes.hasClass('disabledButton')) $save_changes.toggleClass('disabledButton button');
							  }
							else
							  {
								if($save_changes.hasClass('button')) $save_changes.toggleClass('disabledButton button');
							  }
							});
	//INPUT KOLICINA
	
	// UPLOAD FILES
	
	$(".deleteUploadedFile").live('click', function(){ 
							var provera = confirm('Da li zaista želite obrisati ovaj fajl?');
							if(provera)
							  {
								
								var $this_table = $(this).closest('.orderedItemTable');
								var $save_changes = $this_table.find('.orderedItem-saveChanges');
								var $files_change = $this_table.find('.uploadedFilesInfo');
								
								var queue_id = $(this).attr('title');
								var file_name = $(this).siblings('.filename').html();
								/*var amount_value = parseInt($this_table.find('.orderedItem-amountInput').val());
									if(isNaN(amount_value)) amount_value = 0;*/
								
								if($(this).siblings('.blue').length != 0)
								  {
									$('#fileInput').uploadifyCancel(queue_id);
								  }
								deleteUploadedFile($(this),$(this).attr('alt'),queue_id,file_name);
							  }
							});
	
	$(".uploadButton").click(function(){ 
							if($(this).hasClass('disabledButton')) return false;
							else
							  {
								openUploadDialog($(this).attr('title'));
							  }
							});
	
	$('#fileInput').uploadify({
		uploader: URL_TO_THIS_SCRIPT+'/scripts/uploadify-210/uploadify.swf',
		script: URL_TO_THIS_SCRIPT+'/scripts/uploadify-210/uploadify.php',
		checkScript: '/scripts/uploadify-210/check.php',
		folder: upload_dir+'/'+visitor_id+'/'+order_id,
		fileExt: '*.zip;*.rar;*.dxf;*.dwg;*.obj;*.sca;*.ai;*.doc;*.docx;*.xls;*.3ds;*.jpeg;*.jpg;*.gif;*.png;*.bmp',
		fileDesc: 'Dozvoljeni formati',
		wmode: 'transparent',
		queueSizeLimit: 50,
		sizeLimit: 104857600,
		buttonText: 'Dodaj fajl(ove)',
		width: 110,
		height: 30,
		queueID: 'uploadingQueue',
		cancelImg: URL_TO_THIS_SCRIPT+'/scripts/uploadify-210/cancel.png',
		hideButton: true,
		multi: true,
		auto: true,
		onSelect       : function(event, queueID, fileObj) {
								var fileName = cutString(fileObj.name,50,0);
								var fileSizeFormated = new Array();
								fileSizeFormated = formatBytes(fileObj.size);
								$('#fileInputUploader').before('<div id="'+queueID+'" class="uploadingQueue-item notUploaded deleteTarget"><img class="deleteUploadedFile" title="'+queueID+'" src="/scripts/uploadify-210/cancel.png" alt="'+$('#uploadFor').attr('title')+'" /><span class="filename" title="'+fileName+'">'+fileName+'</span><span class="filesize" title="'+fileObj.size+'"> | '+fileSizeFormated[0]+fileSizeFormated[1]+' |</span><span class="infoStatus"></span></div>');
								return false;
						},
		onSelectOnce   : function(event, data) {
								//PODESI SCRIPT DATA ZA PRVI FAJL
								var $nextItem = $('.notUploaded').first();
								$('#fileInput').uploadifySettings('scriptData', {'visitor_id':visitor_id, 'queueID':$nextItem.attr('id'), 'orderID':order_id, 'item_id':$('#uploadFor').attr('title')});
								//RESETUJ PODATKE O KOLICINI PRENETIH PODATAKA
								$('#uploadedByteSize-all, #byteSizeAll').attr('title','0').html('0KB');
								$('#uploadingAllInfo .percent').attr('title','0').html('(0%)');
								//UNESI VREDNOST VELICINE SVIH FAJLOVA
								var allFilesSizeFormated = new Array();
								allFilesSizeFormated = formatBytes(data.allBytesTotal);
								$('#byteSizeAll').html(allFilesSizeFormated[0]+allFilesSizeFormated[1]).attr('title',data.allBytesTotal);
								
								$('#queueMessage').nextAll('.uploaded').removeClass('uploaded');
								$('.uploadingQueue-item').find('.infoStatus').html('');
						},
		onOpen         : function(event, queueID, fileObj) {
								$('#cancelAll-link, #uploadingInfo, #uploadingSelectedInfo').show();
								$('#queueMessage, #closeUploadDialog').hide();
								$('#'+queueID+' .infoStatus').html(' - Transfer u toku.').addClass('blue');
								adjustDialogPosition('#dialog');
								$('#'+queueID).removeClass('notUploaded').addClass('uploadInProgress');
								var $nextItem = $('.notUploaded').first();
								if($nextItem.length != 0) $('#fileInput').uploadifySettings('scriptData', {'visitor_id':visitor_id, 'queueID':$nextItem.attr('id'), 'orderID':order_id, 'item_id':$('#uploadFor').attr('title')});
						},
		onProgress	   : function(event, queueID, fileObj, data) {
							var byteSizeAll = parseInt($('#byteSizeAll').attr('title'));
							var percentage = Math.floor(data.allBytesLoaded/byteSizeAll*100);
							var uploadedSize = new Array();
							var uploadedSize = new formatBytes(data.allBytesLoaded);
							$('#uploadingSelectedInfo .progressbar-span').animate({width: data.percentage+'%'},50,'linear');
							$('#uploadingAllInfo .progressbar-span').animate({width: percentage+'%'},50,'linear');
							$('#uploadingAllInfo .percent').html('('+percentage+'%)').attr('title',percentage);
							$('#uploadingSelectedInfo .fileName').html($('#'+queueID+' .filename').html());
							$('#uploadingSelectedInfo .fileSize').html($('#'+queueID+' .filesize').html()).attr('title',$('#'+queueID+' .filesize').attr('title'));
							$('#uploadingSelectedInfo .percent').html('('+data.percentage+'%)').attr('title',data.percentage);
							$('#uploadedByteSize-all').html(uploadedSize[0]+uploadedSize[1]).attr('title',uploadedSize[0]);
							
							var statusInfo = $('#'+queueID+' .infoStatus').html();
							if(statusInfo.lastIndexOf('...') != -1) statusInfo = statusInfo.replace('...','.');
							else if(statusInfo.lastIndexOf('..') != -1) statusInfo = statusInfo.replace('..','...');
							else statusInfo = statusInfo.replace('.','..');
							$('#'+queueID+' .infoStatus').html(statusInfo);
						},
		onComplete	   : function(event, queueID, fileObj, response, data) {
							
							if(response != 'ok')
							  {
								('#fileInput').uploadifyClearQueue();
								alert(response);
							  }
							$('#'+queueID+' .infoStatus').html(' - Transfer izvršen!').removeClass('blue').addClass('green');
							$('#'+queueID).removeClass('uploadInProgress').addClass('uploaded');
							return false;
							
						},
		onAllComplete  : function(event, data) {
							$('#cancelAll-link, #uploadingSelectedInfo').hide();
							$('#closeUploadDialog').show();
							alert('Transfer fajlova je uspešno izvršen.');
							return false;
						},
		onError	   	   : function(event, queueID, fileObj) {
							$('#'+queueID+' .infoStatus').html(' - Dogodila se greška!!!').removeClass('blue').addClass('red');
						},
		onClearQueue   : function(event) {
							$('#uploadingAllInfo, #uploadingSelectedInfo').find('.progressbar-span').animate({width: '0%'},{
																												duration: 400,
																												easing: 'linear',
																												complete: function(){
																												  $(this).closest('fieldset').find('.fileSize').attr('title','0').html('| 0KB |');
																												  $(this).closest('fieldset').find('#uploadedByteSize-all, #byteSizeAll').attr('title','0').html('0KB');
																												  $(this).closest('fieldset').find('.percent').attr('title','0').html('(0%)');
																												  $('#uploadingSelectedInfo, #uploadingInfo').hide();
																												  $('#queueMessage').show().nextAll('.notUploaded, .uploaded').remove();
																												  $('#closeUploadDialog').show();
																												}
																												});
							return false;
						}
	});
	// UPLOAD FILES
/* K O R P A */


/* M I S C */
	// ALL INPUTS
	$("input.inputOrTextarea-focusOut, textarea.inputOrTextarea-focusOut")
					.focusin(function() { 
							$(this).toggleClass("inputOrTextarea-focusIn inputOrTextarea-focusOut");
							})
					.focusout(function() { 
							$(this).toggleClass("inputOrTextarea-focusIn inputOrTextarea-focusOut");
							});
	// ALL INPUTS
	
	// SEARCHBOX
	 $(".searchbox").focusin(function() { 
							if($(this).val() == $(this).attr("title")) $(this).val("");
							})
					.focusout(function() { 
							if($(this).attr("title") != 'undefined' && $(this).val() == '') 
								$(this).val($(this).attr("title"));
							})
					.bind('keyup mouseleave', function(event){
							var pattern = /q=(.*)&/i;
							var href = $("#search-button").attr('href');
							href = href.replace(pattern, 'q='+$(this).val()+'&');
							$("#search-button").attr('href',href);
							if(event.keyCode == 13) window.open(href,'_self');
							});
	
	// SEARCHBOX
	
	// SUBSCRIBE/UNSUBSCRIBE
	
	$("#subscribe-link").click(function(){ 
							if($(this).hasClass('disabledButton')) return false;
							
							var pattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
							if($("#subscribe-input").val().match(pattern) == null)
							  {
								alert("Morate pravilno uneti email adresu u gornje polje!");
								return false;
							  }
							else
							  {
								subscribe("add-me", $("#subscribe-input").val());
							  }
							});
	$("#unsubscribe-link").click(function(){
							if($(this).hasClass('disabledButton')) return false;
							
							var pattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
							if($("#subscribe-input").val().match(pattern) == null)
							  {
								alert("Morate pravilno uneti email adresu u gornje polje!");
								return false;
							  }
							else
							  {
								subscribe("remove-me", $("#subscribe-input").val());
							  }
							});
	
	$("#subscribe-input").bind('keyup mouseleave', function(){
							var this_value = $(this).val();
							var this_startValue = $(this).attr('title');
							
							if(this_value == this_startValue)
							  {
								if($subscribe.hasClass('button')) $subscribe.toggleClass('button disabledButton');
								
								if(this_value == '') 
								  {
									if($unsubscribe.hasClass('button')) $unsubscribe.toggleClass('button disabledButton');
									
								  }
								else
								  {
									if($unsubscribe.hasClass('disabledButton')) $unsubscribe.toggleClass('button disabledButton');
								  }
							  }
							else if(this_value == '' || this_value == $(this).parent().attr('title'))
							  {
								if($subscribe.hasClass('button')) $subscribe.toggleClass('button disabledButton');
								if($unsubscribe.hasClass('button')) $unsubscribe.toggleClass('button disabledButton');
							  }
							else
							  {
								if($subscribe.hasClass('disabledButton')) $subscribe.toggleClass('button disabledButton');
								if($unsubscribe.hasClass('button')) $unsubscribe.toggleClass('button disabledButton');
							  }
							}).focusin(function() {
							
								if($(this).val() == $(this).parent().attr('title')) $(this).val('');
							
							}).focusout(function() {
								if($(this).val() == '')
								  {
									if($(this).attr('title') == '')
										 $(this).val($(this).parent().attr('title'));
									else 
									  {
										$(this).val($(this).attr('title'));
										if($subscribe.hasClass('button')) $subscribe.toggleClass('button disabledButton');
										if($unsubscribe.hasClass('disabledButton')) $unsubscribe.toggleClass('button disabledButton');
									  }
										
								  }
							});
	// SUBSCRIBE/UNSUBSCRIBE
	
	//SLIDE BOXES
	$("a.expand-showButton").click(function(){ 
							var $this_box = $(this).closest('.expand-div');
							$(this).parent('span').hide();
							$this_box.find('.long-story').slideDown(400);
							});
	$("a.expand-hideButton").click(function(){
							var $this_box = $(this).closest('.expand-div');
							$this_box.find('.long-story').slideUp(400,function(){ $this_box.find('.span-showMore').show(); });
							});
	//SLIDE BOXES
	
	if(first_page == true) $.colorbox({href:'http://3dcrystal3d.com/3rdparty/colorbox/usce.jpg'});
	
	
/* M I S C */
  }

function posetaDetalji(id_posetioca)
  {
	$('body').append('<div id="popupPosete" style="position: fixed; width: 800px; height: 500px; background-color: white; color: black; overflow: auto; left: '+(($(window).width()-800)/2)+'px; top: '+($(window).height()-500)/2+'px; text-shadow: none !important; padding: 2em;">Sačekajte dok se podaci učitavaju... <a href="javascript: posetaDetaljiObrisi();" style="color: red; text-shadow: none !important;">ZATVORI</a></div>');
	//alert($('#popupPosete').html());
	$.ajax({
		url:URL_TO_THIS_SCRIPT+"/posete-ajax.php",
		type: "POST",
		async: false,
		cache: false,
		data: {
				id : id_posetioca
			  },
		dataType: "html",
		success: function(data){
			$('#popupPosete').html(data);
		}
	});
  }

function posetaDetaljiObrisi()
  {
	$("#popupPosete").remove();
  }

$(document).ready(function() { init(); });
