
var searchPrompt = 'Cauta in website';
var useAnimation = true;
var menuTop = new TopMenu();
var arrPage = ["pageClient", "pageYM", "pageDelievery", "pageMessage", "pageSpread"];

function TopMenu()
{
	var thisCopy = this;
	this.arrButton = ["menu-top-client", "menu-top-ym", "menu-top-delievery", "menu-top-message", "menu-top-spread"];
	this.arrPage = null;
	this.pageVisible = '';
	this.iClicked = -1;
	
	this.collapse = function()
	{
		if( !this.isExpanded())
			return;
		
		if( this.pageVisible == '')
			return;
			
		var iClicked = jQuery.inArray(this.pageVisible, this.arrPage);
		if( iClicked == -1)
			return;

		// collapse
		$('#'+this.pageVisible).hide();
		this.pageVisible = '';
		
		if( useAnimation)
		{
			$("#band-menu").toggle("fast");
			$("#band-promo").toggle("fast");
			$("#band-logo").toggle("fast");

			$("#hiddenForm").slideToggle("normal");
		}
		else
		{
			this.show( ['band-menu','band-promo','band-logo']);
			this.hide( ['hiddenForm']);
		}
		
		return;
	}
	
	this.expand = function(nPage)
	{
		if( (nPage>=0) && (nPage<5))
		{
			var btnId = '#' + this.arrButton[nPage] + ' a';
			$(btnId).trigger('click');
		}
	}

	this.init = function()
	{
		this.arrPage = arrPage;
		$('#close-top a').click(function()
		{
			$(this).parent().hide();
			thisCopy.collapse();
		});
		
		$('#menu-top a').click(function()
		{
			var clickedBtnId = $(this.parentNode).attr('id');
			var iClicked = jQuery.inArray(clickedBtnId, thisCopy.arrButton);
			var pageClicked = iClicked!=-1 ? thisCopy.arrPage[iClicked] : '';
			
			$(this).blur();

			if( !thisCopy.isExpanded())
			{
				// expand
				if( useAnimation)
				{
					$("#band-menu").toggle("fast");
					$("#band-promo").toggle("fast");
					$("#band-logo").toggle("fast", function(){ $('#close-top').show();} );
					$("#hiddenForm").slideToggle("normal");
				}
				else
				{
					thisCopy.hide( ['band-menu','band-promo','band-logo']);
					thisCopy.show( ['hiddenForm']);
					$('#close-top').show();
				}
				
				//$('#close-top a').show();
				
			}
			else
			{
				if( thisCopy.pageVisible == pageClicked)
				{
					// collapse
					$('#'+thisCopy.pageVisible).hide();
					thisCopy.pageVisible = '';
					
					if( useAnimation)
					{
						$("#band-menu").toggle("fast");
						$("#band-promo").toggle("fast");
						$("#band-logo").toggle("fast");
			
						$("#hiddenForm").slideToggle("normal");
					}
					else
					{
						thisCopy.show( ['band-menu','band-promo','band-logo']);
						thisCopy.hide( ['hiddenForm']);
					}
					
					return;
				}
			}

			if( thisCopy.pageVisible == pageClicked)
			{
				return;
			}
							
			if( thisCopy.pageVisible != '')
			{
				$('#'+thisCopy.pageVisible).hide();
				thisCopy.pageVisible = '';
			}
			
			$('#'+pageClicked).show();
			thisCopy.pageVisible = pageClicked;

			if( $('#'+pageClicked).data("loaded") != 1)
			{
				$('#'+pageClicked).data("loaded", 1);
				$('#'+pageClicked + " .content").html("<div class=\"loading\">Se incarca, va rugam asteptati ...</div>");
				$('#'+pageClicked + " .content").load(
					pageClicked+".php",
					function (responseText, textStatus, XMLHttpRequest) 
					{
						//this; // dom element
						if( thisCopy.pageVisible == 'pageYM')
						{
							if( $('#operatorsYahoo').data("readonce") != 1)
							{
								blitzCheckYahooStatus();
								$('#operatorsYahoo').data("readonce", 1) ;
							}
						}
						else if( thisCopy.pageVisible == 'pageClient')
						{
							var oPageClicked = $('#'+pageClicked);
							
							//alert(oPageClicked.html());

							var oForm = $("#formLogin");
							if( oForm)
							{
								oForm.validate();
								oForm.submit( function() { 
									var options = { 
										beforeSubmit:  showRequest,  // pre-submit callback 
										success:       showResponseLogin,  // post-submit callback 
										url:			thisCopy.pageVisible+".php" ,
										type:			'post' 
								 
										// other available options: 
										//url:       url         // override for form's 'action' attribute 
										//type:      type        // 'get' or 'post', override for form's 'method' attribute 
										//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
										//clearForm: true        // clear all form fields after successful submit 
										//resetForm: true        // reset the form after successful submit 
								 
										// $.ajax options can be used here too, for example: 
										//timeout:   3000 
									}; 
		
									// inside event callbacks 'this' is the DOM element so we first 
									// wrap it in a jQuery object and then invoke ajaxSubmit 
									$(this).ajaxSubmit(options); 
							 
									// !!! Important !!! 
									// always return false to prevent standard browser submit and page navigation 
									return false; 
								}); 
							} 
						}
						else
						{
							var oPageClicked = $('#'+pageClicked);

	//						$("form", oPageClicked).submit( function(){
	//							alert(this.id);
	//							return false;
	//						});

							
							var oForm = $("form", oPageClicked);
							if( oForm)
							{
								oForm.validate();
								oForm.submit( function() { 
									var options = { 
										//target:        '#output2',   // target element(s) to be updated with server response 
										beforeSubmit:  showRequest,  // pre-submit callback 
										success:       showResponse,  // post-submit callback 
										url:			thisCopy.pageVisible+".php" ,
										type:			'post' 
									}; 
		
									// inside event callbacks 'this' is the DOM element so we first 
									// wrap it in a jQuery object and then invoke ajaxSubmit 
									$(this).ajaxSubmit(options); 
							 
									// !!! Important !!! 
									// always return false to prevent standard browser submit and page navigation 
									return false; 
								}); 
							} 
						} 
					});
			}
		});
	}

	this.isExpanded = function()
	{
		return $('#hiddenForm').css('display') != 'none';
	}

	this.show = function ( arGroup)
	{
		for(var i=0; i<arGroup.length; i++)
		{
			$('#'+arGroup[i]).show();
		}
	}

	this.hide = function( arGroup)
	{
		for(var i=0; i<arGroup.length; i++)
		{
			$('#'+arGroup[i]).hide();
		}
	}

}



$(document).ready( function()
{
	externalLinks();
	
	menuTop.init();
	
	if( window.location.search.indexOf( 'action=expand') != -1)
	{
		menuTop.expand(0);
	}
	
	$('#footer h2').each(function()
	{
		applyShadow( this, "#000", {left:2,top:6});
	});
	
	$('#menu-top a').hover(
		function(){
			$(this).parent().addClass('selected');
		},
		function(){
			$(this).parent().removeClass('selected');
		}
		);
	
//	$('.pane3-title h2').each(function()
//	{
//		applyShadow( this, "#000", {left:2,top:6});
//	});
	
	$('#td-tip-persoana input, #td-tip-persoana label').click(function(){
		
		if( $('#td-tip-persoana input:checked').val() == 'Fizica')
		{
			$('.red2').hide();
		}
		else
		{
			$('.red2').show();
		}
	});
	
	$('#td-tip-livrare input, #td-tip-livrare label').click(function(){
		
		if( $('#td-tip-livrare input:checked').val() == 'livrare')
		{
			$('.dlivrare2').removeClass("dlivrare2").addClass("dlivrare");
			//$('.dlivrare').show();
		}
		else
		{
			$('.dlivrare').removeClass("dlivrare").addClass("dlivrare2");
			//$('.dlivrare').hide();
		}
	});
	
	$('#menu-main-sevices a').data("hover", 0);
	$('#services-menu').data("hover", 0);
	
	$('#menu-main-services a').hover( 
		function() {
			$(this).data("hover", 1); 
			$('#services-menu').fadeIn();
			},
		function() { 
			$(this).data("hover", 0);
			setTimeout( function()
				{
					if( ($('#menu-main-services a').data("hover") == 0) && ($('#services-menu').data("hover") == 0) )
					{
						$('#services-menu').fadeOut();
					}
				}, 300);
			}
	);
	
	$('#services-menu').hover( 
		function() {
			$(this).data("hover", 1); 
			},
		function() {
			$(this).data("hover", 0); 
			setTimeout( function()
				{
					if( ($('#menu-main-services a').data("hover") == 0) && ($('#services-menu').data("hover") == 0) )
					{
						$('#services-menu').fadeOut();
					}
				}, 300);
			}
	);
	
	$('#checkYahooStatusNow').click(function()
	{
		blitzCheckYahooStatus(this);
	});
	
	$('#search-input').focus(function()
	{
		var val = $(this).val();
		if( val == searchPrompt)
		{
			$(this).val('');
		}
	});
	
	$('#search-input').blur(function()
	{
		var val = $(this).val();
		if( val == '')
		{
			$(this).val(searchPrompt);
		}
	});

	$('#logo-promo-slides').cycle({ 
		fx: 'scrollUp', 
		timeout: 6000, 
		delay:  -2000,
		next:   '#next2',
		prev:   '#prev2'
	});
	$('#pause2').click(function() { $('#logo-promo-slides').cycle('pause'); return false; });
	$('#play2').click(function() { $('#logo-promo-slides').cycle('resume'); return false; });
	
	
	jQuery.each( arrPage, function(i, val)
	{
		var root = val.substring(4).toLowerCase();
		var link = '#scrollto-' + root;
		
		$(link).click( function()
		{
			if(menuTop)
				menuTop.collapse();
				
			$.scrollTo(
				{left:0, top:0}, 
				500, 
				{onAfter: function()
					{
						$('#menu-top-'+root+' a').trigger('click');
					}
				});
		});
	});
	
}); // $(document).ready( function()


// pre-submit callback 
function showRequest(formData, jqForm, options) 
{ 
	if( !jqForm.valid())
		return false;
	
	$("table", jqForm).hide();
   	$(".response", jqForm).hide();
	$(".sender", jqForm).show();
    return true; 
} 
 
// post-submit callback 
function showResponse(responseText, statusText, jqForm)  
{ 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.');
    
    if( statusText == 'success')
    {
    	if( responseText == '')
    	{
	    	jqForm.clearForm();
	    	$(".response", jqForm).html("Mesajul a fost transmis cu succes!");
    	}
    	else
    	{
	    	$(".response", jqForm).html(responseText);
    		
    	}
    	
    	setTimeout( function(){
			$(".sender", jqForm).hide();
			$(".response", jqForm).show();
			$("table", jqForm).show();
			jqForm.show();
			},
			1000
		);
    }
    else
    {
    	jqForm.show();
    } 
} 

function showResponseLogin(responseText, statusText, jqForm)  
{ 
    if( statusText == 'success')
    {
    	if( responseText == '')
    	{
    		// no errors
//    		loc = window.location.href;
//    		if( loc.indexOf('index.php') == -1)
//    		{
//    			loc = loc+'index.php?page=prima';
//    		}
//    		loc = loc+'&action=expand'
//    		window.location = loc;
    		window.location = "http://"+location.host+location.pathname+"?page=comenzi";
    	}
    	else
    	{
	    	$(".response", jqForm).html(responseText);
	    	setTimeout( function(){
				$(".sender", jqForm).hide();
				$(".response", jqForm).show();
				$("table", jqForm).show();
				jqForm.show();
				},
				1000
			);
    		
    	}
    }
    else
    {
    	jqForm.show();
    } 
} 

$(function() 
{
	$('#pause').click(function() { $('#slides').cycle('pause'); return false; });
	$('#play').click(function() { $('#slides').cycle('resume'); return false; });
	
	$('#slideshow').hover(
		function() { $('#controls').fadeIn(); },
		function() { $('#controls').fadeOut(); }
	);
/*			
			$('#slides').cycle({
				fx:     'fade',
				speed:   700,
				timeout: 1000,
				next:   '#next',
				prev:   '#prev',
				after:   onAfter
			});
*/			
	$('#slides').cycle({ 
		next:   '#next',
		prev:   '#prev',
		speed:   'fast',
		timeout: 1000,
		after:   onAfter,
		fx: 'custom', 
/*				
				cssBefore: {  
					opacity: 0,
					display: 'block'
				}, 
				animIn: {  
					opacity: 1,
					display: 'block'
				}, 
				animOut: {  
					opacity: 1,
					display: 'none'
				}, 
				cssAfter: {  
					opacity: 0,
					display: 'none'
				} 
*/				
		cssBefore: {  
			opacity: 0,
			display: 'block'
		}, 
		animIn: {  
			opacity: 1
		}, 
		animOut: {  
			opacity: 1
		}, 
		cssAfter: {  
			opacity: 0
		} 
		
	});
	
});

function onAfter()
{
	var cn = this.className;
	if( cn.indexOf('pause-') == 0)
	{
		$('#slides').cycle('pause');
		var msecs = parseInt(cn.split('-')[1]);
		setTimeout( 
			function() { $('#slides').cycle('resume');}, 
			msecs);
	}
}

function blitzCheckYahooStatus(element)
{
	if( element)
	{
		$(element).blur();
	}
	$('#operatorsYahoo').html('');
	
	$.ajax(
	{
		method: "get",
		url: "ym.php",
		data: "page=operators",
		beforeSend: function()
			{
				$('#checkYahooStatus-wait').show("fast"); //show loading just when link is clicked
			},
		complete: function()
			{
				$('#checkYahooStatus-wait').hide("fast"); //stop showing loading when the process is complete
			},
		success: function(html)
			{
				//so, if data is retrieved, store it in html
				$('#operatorsYahoo').html(html);
				$('#operatorsYahoo').show('slow');
			}
	});
}

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 difolder(val)
{
	var name = prompt("Copiaza numele folderului in bara de adrese a FileExplorer\npentru a deschide folderul cu fisiere atasate comenzii.", val);
}

function init_comenzi()
{
	$(".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("ajax_fileinfo.php", {cmd: id}, function(data) {
					$("#finfo-"+id).html(data);
					});
					
				$(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);				
		}
		
	});
}