
$(document).ready( function() 
{
	$('#form-poza-ta2').submit( function(){
		elementLock( this, true, "Va rugam asteptati, se incarca imaginea ...");
		return true;
	});

	$('#p-portofoliu-adaugare').submit( function(){
		elementLock( this, true, "Va rugam asteptati, se incarca imaginea ...");
		return true;
	});
	
	
	// $(document).pngFix();
	externalLinks();
	
	$('#slides img')
		.click( function() {
			gotoPage('acasa');
			return false;
		})
		.css({cursor:'pointer'});

	$('#slideshow').hover( 
		function() { $('#controls').fadeIn(); }
		,
		function() { $('#controls').fadeOut(); }
	);

	$('#pause').click( function() {
		$('#slides').cycle('pause');
		return false;
	});

	$('#play').click( function() {
		$('#slides').cycle('resume');
		return false;
	});
/*
	$('#prev').click( function() {
		$('#slides').cycle.prev(
		{
			speed : 100
			,timeout : 100
		});
		return false;
	});
*/
	$('#slides').cycle( {
		fx :'fade'
		,speed :2000
		,next: '#next'
		,prev: '#prev'
		,after : function() {
			var cn = this.className;
			if (cn.indexOf('pause-') == 0) {
				$('#slides').cycle('pause');
				var msecs = parseInt(cn.split('-')[1]);
				setTimeout( function() {
					$('#slides').cycle('resume');
				}, msecs);
			}
		}
	});

});

jQuery.fn.offsetTop = function() {
	var e = this.get(0);
	if (!e.offsetParent)
		return e.offsetTop;
	return e.offsetTop + $(e.offsetParent).offsetTop();
};

function getOffsetTop(e)
{
	if(!e.offsetParent)
		return e.offsetTop;
	
	return e.offsetTop + getOffsetTop(e.offsetParent);
}

function focusFFE() 
{
	var firstField;
	$.each( ['input', 'select', 'textarea'], function() {
		var field = $('form ' + this + ':visible:enabled:first').get(0);
		if (field)
			if (!firstField || getOffsetTop(field) < getOffsetTop(firstField))
				firstField = field;
	});
	if( firstField)
		firstField.focus();
}

function focusEl(id) 
{
	var firstField = document.getElementById(id);
	if( firstField)
		firstField.focus();
}

function externalLinks() {
	if (!document.getElementsByTagName)
		return;

	var anchors = document.getElementsByTagName("a");
	for ( var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href")
				&& anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}

function applyShadow(targetElement, shadowColor, offset) {
	if (typeof (targetElement) != 'object') {
		targetElement = document.getElementById(targetElement);
	}

	var value = targetElement.firstChild.nodeValue;
	targetElement.style.position = 'relative';
	targetElement.style.zIndex = 1;

	var newEl = document.createElement('span');
	newEl.appendChild(document.createTextNode(value));
	newEl.className = 'shadowed';
	newEl.style.color = shadowColor;
	newEl.style.position = 'absolute';
	newEl.style.left = offset.left + 'px';
	newEl.style.top = offset.top + 'px';
	newEl.style.zIndex = -1;

	targetElement.appendChild(newEl);
}

function clearFormValues(namePrefix)
{
	$("form input:text[name^='"+namePrefix+"']").val('');
}

function gotoPage(page)
{
	window.location = "http://" + location.host + location.pathname + "?page="+page;
}

function findPos(obj) {
	var cleft = ctop = 0;
	if (obj.offsetParent) 
	{
		do {
			cleft += obj.offsetLeft;
			ctop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	//return [cleft, ctop];
	return {left:cleft, top:ctop};
}

function hoverFading(elem)
{
	$(elem)
		.css('opacity', 0.6)
		.hover( 
			function(){
				$(this).stop();
				$(this).animate({'opacity' : 1}, 600);
			}
			,
			function(){
				$(this).stop();
				$(this).animate({'opacity' : 0.6}, 600);
			}
		);
}

function pozaTa()
{
	// comanda acum!
	hoverFading('.cmdPozata');
	
	$('a.multicanvas-link').click( function(e){ 
		multicanvasShow( $(this).text().replace(/ /g,""), '');
		return false;
	})
		
	function animatePozaTa(image)
	{
		var time = 500;
		var animate = true;

		var $img = $(image);
		$img.wrap('<div style="position: relative; overflow: hidden; width:'+
			$img.outerWidth() + 'px; height:'+
			$img.outerHeight() + 'px;"></div>');
		$div = $img.parent();
		$clone = $img.clone();
		$clone.appendTo( $div);
		$clone.attr('src', $img.attr('src').replace('room-',''));
		
		$img.css({'position' : 'absolute', 'z-index' : 2});
		$clone.css({'position' : 'absolute'});

		
		$('<img class="loupe" src="images/loupe24.jpg" alt="" title="Pozitioneaza cursorul de maus peste poza si in afara ei pentru a vedea cele doua imagini">').appendTo($div);
		
		if( animate)
		{
			$img.hover( 
				function(){
					$img.stop();
					$img.animate(
						{'opacity' : 0}
						,time
						);
				}
				,
				function(){
					$img.stop();
					$img.animate(
						{'opacity' : 1}
						,time
						);
				}
			);
		}
		else
		{				
			$div.hover( 
				function(){
					$img.hide();
				}
				,
				function(){
					$img.show();
				}
			);
		}
	}
		
	$('img.nice-pics').each( function(){
		
		if( this.src.indexOf('/room-') != -1)
		{
			if( this.complete)
				animatePozaTa(this);
			else
				this.onload = function(){ animatePozaTa(this);}
		}
	});
}

function makeCollapser(domNode, label, collapse)
{
	var jNode = $(domNode);
	if( jNode.length == 0)
		return;
		
	var cclass = "collapser";
	if( collapse)
		label = "<span>+</span> "+label;
	else
		label = "<span>-</span> "+label;
	jNode.before('<div><div><a class="'+cclass+'" href="" title="deschide sau inchide zona">'+label+'</a></div> <div class="collapse-container"></div> </div>');
	var jDiv = jNode.prev();
	var jContainer  = $('div:last',jDiv);
	$('a.'+cclass, jDiv).click(function(){
		var jSpan = $('span', this);
		var label = jSpan.text();
		if( label=='+')
		{
			label='-';
		}
		else
		{
			label='+';
		}
		jSpan.text(label);
		jContainer.toggle('fast');
		$(this).blur();
		
		return false;
	});
	
	jContainer.append(jNode);
	if( collapse)
		jContainer.hide();
}

function selectRama(id_dimens, oThis, params)
{
	var $divImage = $(oThis).parent();
	$divImage.after('<div id="wnd-rame" style="height:220px; overflow:hidden; border:2px solid #9D5CC0; background-color: #fff;">' +
		'<div id="wnd-rame-bar" style="height:20px; overflow:hidden; text-align:right; background-color:#eee; border-bottom:1px solid #ccc; padding:0 1px;">' +
			'<a href="" class="collapser">inchide</a>' +
		'</div>' +
		'<div id="wnd-rame-content" style="height:200px; overflow:auto;">' +
			'<div id="loader" style="background: #fff url(images/lightbox/lightbox-ico-loading.gif) no-repeat center center scroll; height: 100%"></div>'+
		'</div>' +
		'</div>');
	var $divWnd = $('#wnd-rame');
	$.get(
		'a-ajax-rame.php', 
		{id: id_dimens}, 
		function(data)
		{
			$('#wnd-rame-content').html(data);
			$('#wnd-rame-content div.rm-container').hover(
				function(){ $(this).css({backgroundColor: '#e4d9eb'});},
				function(){ $(this).css({backgroundColor: ''});}
			);
			
			$('#wnd-rame div.rm-container').click(function()
			{
				var $div = $(this);

				params.id_rama = this.id;
				
				$.get(
					'a-ajax-cos.php' 
					,params 
					,function(data)
					{
						data = jQuery.trim(data);
						if(data != "")
						{
							alert( data);
							return;
						}
						
						window.location.reload();
					}
				);
				
				$('#wnd-rame-bar a').trigger('click');
			});
		}
	);
	
	var api = $divWnd.expose({api: true, color: '#000', loadSpeed:0, closeSpeed:0});
	api.load();
	api.onClose(function(){ 
		$divWnd.remove();
	});
	
	$('#wnd-rame-bar a').click(function(){
		$divWnd.remove();
		api.close();
		return false;
	});
}

function getCartSelected()
{
	return $("#fcart :checkbox:checked").length;
}

function initCos()
{
	$('table.list :checkbox').click( function(e)
	{ 
		var $tr = $(this.parentNode.parentNode);
		var $trAssoc = false;
		if( $tr.is('.rama'))
		{
			$trAssoc = $tr.prev();
		}
		else
		{
			if( $tr.next().is('.rama'))
			{
				$trAssoc = $tr.next();
			}
		}

		if( this.checked)
		{
			$tr.addClass('selected');
			if( $trAssoc)
			{
				$trAssoc.addClass('selected');
				var chk = $(':checkbox:first', $trAssoc).get(0);
				chk.checked = true;			
			}
		}
		else
		{
			$tr.removeClass('selected');
			if( $trAssoc)
			{
				$trAssoc.removeClass('selected');
				var chk = $(':checkbox:first', $trAssoc).get(0);
				chk.checked = false;			
			}
		}
		e.stopPropagation();
	});
			
	$('table.list td.header2').click( function(e)
	{ 
		var $tr = $(this.parentNode);
		var chk2 = $(':checkbox', this).get(0);
		var $trAssoc = false;
		if( $tr.is('.rama'))
		{
			$trAssoc = $tr.prev();
		}
		else
		{
			if( $tr.next().is('.rama'))
			{
				$trAssoc = $tr.next();
			}
		}
				
		if( chk2.checked)
		{
			$tr.removeClass('selected');
			if( $trAssoc)
			{
				$trAssoc.removeClass('selected');
				var chk = $(':checkbox:first', $trAssoc).get(0);
				chk.checked = false;			
			}
		}
		else
		{
			$tr.addClass('selected');
			if( $trAssoc)
			{
				$trAssoc.addClass('selected');
				var chk = $(':checkbox:first', $trAssoc).get(0);
				chk.checked = true;			
			}
		}
		chk2.checked = !chk2.checked;
	});

	$('#cmdSelAll').click( function(e){
		$('table.list td.header2').each( function(e)
		{ 
			var tr = this.parentNode;
			var chk = $(':checkbox', this).get(0);
			if( !chk.checked)
			{
				$(tr).addClass('selected');
				chk.checked = !chk.checked;
			}
		});
		return false;
	});

	$('#cmdSelNone').click( function(e){
		$('table.list td.header2').each( function(e)
		{ 
			var tr = this.parentNode;
			var chk = $(':checkbox', this).get(0);
			if( chk.checked)
			{
				$(tr).removeClass('selected');
				chk.checked = !chk.checked;
			}
		});
		return false;
	});
	
	$('.cartops .collapser').click( function(e){
		
		if( this.id.indexOf('sterge-') == 0)
		{
			var idp = this.id.split('-')[1];
			
			$.get(
				'a-ajax-cos.php' 
				,{id: idp, cmd:2} 
				,function(data)
				{
					data = jQuery.trim(data);
					if(data != "")
					{
						alert( data);
						return;
					}
					
					window.location.reload();
				}
			);
		}
		else if( this.id.indexOf('adaugarama-') == 0)
		{
			var ids = this.id.split('-');
			var id_cart_item = ids[1];
			var id_dimens = ids[2];
			selectRama(id_dimens, this, {cmd:4, id_dimens:id_dimens, id:id_cart_item});						
		}
		else if( this.id.indexOf('modificarama-') == 0)
		{
			var ids = this.id.split('-');
			var id_cart_item = ids[1];
			var id_dimens = ids[2];
			selectRama(id_dimens, this, {cmd:5, id_dimens:id_dimens, id:id_cart_item});						
		}
		
		return false;
	});
	

	$(":submit[name='btnGolire']").click( function(e){
		if( !confirm('Aceasta operatie va sterge toate produsele din cos. Continuati?'))
		{
			return false;
		}
	});
	
	$(":submit[name='btnComanda']").click( function(e){
		
		if( getCartSelected() == 0)
		{
			alert('Va rugam sa selectati produsele din cos pe care doriti sa le comandati!');
			return false;
		}
		return true;
	});
	
	$('#fcart').submit(function(e){
		
		$("[name^='hidCheck']:hidden").each(function (i){
			var v = $(':checkbox:first', this.parentNode.parentNode).get(0).checked ? "1" : "0";
			$(this).val( v);
		});
		
		return true;
	});
}

function initComanda()
{
	$(document).ready( function() 
	{
		$('#chkAcord').click(function(e){
			var checked = this.checked ? '' : 'disabled';
			$('#btnFinalizare').attr('disabled', checked);
		});
	});
}

function initComenzi()
{
	$(".btnInfoFiles").click(function(e)
	{
		$(this).blur();
		var row = $(this).parents("tr").get(0);
		var image = $("img", this);
		var src = image.attr("src");
		var bIsColapsed = src.indexOf("expand") != -1;
		if( bIsColapsed)
		{			
			if( $(this).data("expanded-once"))
			{
				$(row).next().show();
			}
			else
			{
				var id = $(row).attr("id");
				id = id.replace("comanda-", "");
				$("<tr><td class=\"header\"></td><td colspan=\"6\" class=\"finfo\" id=\"finfo-"+id+"\"><img src=\"images/loading.gif\" alt=\"\"></td></tr>").insertAfter(row);
				$.get(
					"a-ajax-comanda.php", 
					{id: id}, 
					function(data) {
						$("#finfo-"+id).html(data);
						externalLinks();
					});
					
				$(this).data("expanded-once", true);					
			}
			src = src.replace("expand", "colapse");
			image.attr("src", src);
		}
		else
		{
			$(row).next().hide();
			src = src.replace("colapse", "expand");
			image.attr("src", src);				
		}
		
	});
}

function elementLock( node, bSet, message)
{
	var $node = $(node);
	if( bSet)
	{
			var curtop = curleft = 0;
			var obj = node;
			if (obj.offsetParent)
			{
				do {
					curtop += obj.offsetTop;
					curleft += obj.offsetLeft;
				} while (obj = obj.offsetParent);
			}
			
			var $clone = $('<div class="xlocker">'+message+'</div>');
			$(document.body).append($clone);

			$clone.css( {
				'position' : 'absolute'
				, left : curleft
				, top : curtop
				, height : $node.height()
				, width : $node.width()
				, 'z-index':10000
				, 'background' : '#B26AD9 url(images/lock.gif) no-repeat center center scroll'
				, 'opacity' : 0.7
				, border : '1px solid #bbb'
				, cursor : 'wait'
				, 'text-align' : 'center'
				, color : '#fff'
				, 'font-size' : '18pt'
				});
				
			$node.data("locked", $clone.get(0));
	}
	else
	{
		if( $node.data("locked"))
		{
			$($node.data("locked")).remove();
		}
	}
}


function initReduceri()
{
	var fmtText = '%s'+
		'<br>'+
		'Promotie valabila in perioada: <span>%s - %s</span>.'+
		'<br>'+
		'Codul promotiei este: <span>%s</span>.'+
		'<br>'+
		'Introduceti codul in formularul de comanda pentru a beneficia de aceasta reducere.';
	var $txtCod = null;
	var $txtDescr = null;
	var $txtProcent = null;
	var $dataValidBegin_d = null; // dataValidBegin[d]
	var $dataValidBegin_m = null; // dataValidBegin[M]
	var $dataValidBegin_y = null; // dataValidBegin[Y]
	var $dataValidEnd_d = null; // dataValidEnd[d]
	var $dataValidEnd_m = null; // dataValidEnd[M]
	var $dataValidEnd_y = null; // dataValidEnd[Y]
	
	function updatePromo()
	{
		var mesaj = $txtDescr.val();
		var cod = $txtCod.val();
		var procent = $txtProcent.val();
		var dataValidBegin = sprintf('%02s.%02s.%s', $dataValidBegin_d.val(), $dataValidBegin_m.val(), $dataValidBegin_y.val());
		var dataValidEnd = sprintf('%02s.%02s.%s', $dataValidEnd_d.val(), $dataValidEnd_m.val(), $dataValidEnd_y.val());
		
		mesaj = mesaj.replace(/\n/g, "<br>");
		var html = sprintf(fmtText, mesaj, dataValidBegin, dataValidEnd, cod);

		$('#main-promo').html(html);
	}
	
	$(document).ready( function() 
	{
		$txtCod     = $("[name='txtCod']");
		$txtDescr   = $("[name='txtDescr']");
		$txtProcent = $("[name='txtProcent']");
		$dataValidBegin_d = $("[name='dataValidBegin[d]']");
		$dataValidBegin_m = $("[name='dataValidBegin[M]']");
		$dataValidBegin_y = $("[name='dataValidBegin[Y]']");
		$dataValidEnd_d = $("[name='dataValidEnd[d]']");
		$dataValidEnd_m = $("[name='dataValidEnd[M]']");
		$dataValidEnd_y = $("[name='dataValidEnd[Y]']");
		
		$('<h3 style="text-align:center;">Previzualizare promotie</h3> <p id="main-promo"></p>').insertBefore( $('#form-reduceri'));
		
		updatePromo();
		
		$txtCod.keyup(function(){
			updatePromo();
			});
		$txtDescr.keyup(function(){
			updatePromo();
			});
		$txtProcent.keyup(function(){
			updatePromo();
			});
		$dataValidBegin_d.change(function(){
			updatePromo();
			});
		$dataValidBegin_m.change(function(){
			updatePromo();
			});
		$dataValidBegin_y.change(function(){
			updatePromo();
			});
		$dataValidEnd_d.change(function(){
			updatePromo();
			});
		$dataValidEnd_m.change(function(){
			updatePromo();
			});
		$dataValidEnd_y.change(function(){
			updatePromo();
			});
	});
}

