$(function() {	
	initOrder();
	initNote();
	initLogin();
	initUpload();
	initSettings();
	
	// fancybox
	$(".open-popup").fancybox({
		'href' : $(".open-popup").attr('href'),
		'titleShow'		: false,
		'padding' : 20,
		'centerOnScroll'  : true,
		'overlayOpacity' : 0.7,
		'overlayColor' : '#000000',
	});
	
	$('a[rel=external]').attr('target', '_blank');
	
	var url = window.location.href; 
	if(url.search(/#login/i) != -1) {			
		$(".open-popup[href=#login]").click();		
	}  
	if(url.search(/#settings/i) != -1) {	
		$(".open-popup[href=#settings]").click();
	}
	
	// carousel
	var visible = 2; 
	var scroll = 2; 
	var speed = 350; 
	var next = $('#carousel-next'); 
	var prev = $('#carousel-prev'); 
	var auto = true; 
	var delay = 5; 
	var stopAutoAfterClick = false; 
	$('#carousel').circularCarousel(visible, scroll, speed, prev, next, auto, delay, stopAutoAfterClick);  
	
	// tabs
	$('.tabs a').click(function(){
		switchTabs($(this));
	}); 
	switchTabs($('.defaulttab'));
	
	// accordion
	$('#faq div:not(:first)').hide();
	$('#faq h2:first').addClass('active');
	$('#faq h2').click(function(){
		$('#faq h2').removeClass('active');
		$('#faq div').slideUp();
		$(this).toggleClass('active');
		$(this).next().slideToggle();
		return false;
	});

	
});
function initOrder() { 
	$('#form-create-order').submit(function() {		
    if (validate(this)) {
			var id = '#obutton';
			var img = '<img src="img/loader.gif" alt="" class="loader" />';
			$(id).parent().append(img);	
		}else 
		return false
  });
  $('#form-create-order').iframer({ 
    onComplete: function(html){ 
    	var id = '#summary';
			var button = '#obutton';
			$('.loader', id).remove();
      $(id).append(html);
			$(button).attr('disabled', 'disabled');
      setTimeout(function() {
      	$('.response', id).remove();      	
				$(button).removeAttr("disabled");        
      }, 15000)      
    } 
	}); 	
  
  $('#form-delete-order').submit(function() {
  	if (confirm('Are you sure you want to delete?')) {
			$.ajax({        
				type: 'POST',
				url: $(this).attr('action'),
				data: $(this).serialize(),
				success: function(r) {
					if(r) {
						location.href='./dashboard';
					} else {
						alert('Error');
					}
				}
			});
		}
		return false;
  });
	
} 
function initUpload() { 
  $('#form-upload-file').iframer({ 
    onComplete: function(html){ 
    	var id = '#form-upload-file';
		  $(id).append(html);
			element.before(html);
      setTimeout(function() {
      	$('.response', id).remove();
      }, 15000)      
    } 
	}); 	
} 
function initNote() { 
	$('#form-create-note').submit(function() {
		var id = '#'+$(this).attr('id');
		var element = $('.row:first', this);
		var imgLoader = '<img src="./img/ajax-loader.gif" alt="Loading..." class="loader">';
		var loader = $('.row:first label', this);
		
		if (validate(this)) { 
			$(loader).append(imgLoader);
			$('button', id).attr("disabled", "disabled");
			
			$.ajax({        
				type: 'POST',
				url: $(this).attr('action'),
				data: $(this).serialize(),
				success: function(html) {
					$('.loader', id).remove();
					$('button', id).removeAttr('disabled');				
					
					if(html == 0) {   
						$(element).before('<div class="notice error">Error</div>');
					}
					else {
						var id = '#add-note';
						$(id).before(html);
						$('#form-create-note').get(0).reset();
					}   				
					setTimeout(function() {
						$('.notice', id).remove();						
					}, 15000)          
				}
			});
		}
		return false;
  });	
} 
function initLogin() {
  $('#form-login').submit(function() {
		var id = '#'+$(this).attr('id');
		var element = $('.row:first', this);
		var imgLoader = '<img src="./img/ajax-loader.gif" alt="Loading..." class="loader">';
		var loader = $('h2:first', this);
				
    if (validate(this)) { 
			$(loader).append(imgLoader);
			$('button', id).attr('disabled', 'disabled');
			$.ajax({        
        type: 'POST',
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function(r) {
					$('.loader', id).remove();	
					$('button', id).removeAttr('disabled');			
							
          if (r == 1) {
	          location.href='./dashboard';
          } else {
						element.before('<div class="notice error">Wrong Email or Password</div>')
					} 	
					setTimeout(function() {
						$('.notice', id).remove()						
					}, 5000) 				                                  
      	}
    	})	
		}		
		return false		
  });
  $('#form-lost-password').submit(function() {    
		var id = '#'+$(this).attr('id');
		var element = $('.row:first', this);
		var imgLoader = '<img src="./img/ajax-loader.gif" alt="Loading..." class="loader">';
		var loader = $('h2:first', this);
		
    if (validate(this)) { 
			$(loader).append(imgLoader);
			$('button', id).attr('disabled', 'disabled');
			
      $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function(r) { 
					$('.loader', id).remove();	
					$('button', id).removeAttr('disabled');			
					         
          if (r == 1) {
            element.before('<div class="notice success">Your password successfully sent</div>')
          } else {
            element.before('<div class="notice error">Internal error</div>')
          }  
					setTimeout(function() {
						$('.notice', id).remove()
					}, 5000)                             
      	}
    	})
    }
    return false
  });
    
}   
function initSettings() {      
	$('#settings form').submit(function() {
		var id = '#'+$(this).attr('id');
		var element = $('.row:first', this);	
		var imgLoader = '<img src="./img/ajax-loader.gif" alt="Loading..." class="loader">';
		var loader = $('h2:first', this);
		
		if(validate(id)) {
			$(loader).append(imgLoader);
			$('button', id).attr('disabled', 'disabled');
			
			$.ajax({        
				type: 'POST',
				url: $(this).attr('action'),
				data: $(this).serialize(),
				success: function(html) { 
					$('.loader', id).remove();	
					$('button', id).removeAttr('disabled');			
					
					$(element).before(html);        
					setTimeout(function() {
						$('.notice', id).remove()
					}, 3000)                         
				}
			})
		}
		return false;
	});		
} 

function evalPrice() { 

	$('input.radio:checked').each(function() {
		var t = $(this).parent('label').parent('p').children('span').children('em').html();
		var o = $(this).parent('label').parent('p').parent('div').children('h5').html();
		var v = $(this).parent('label').children('small').html();
		$(this).parent('label').parent('p').parent('div').children('input.oh').val(t);
		$(this).parent('label').parent('p').parent('div').children('input.olh').val(o + ' ' + v + '\n');
	});
	$('input.baseprice:checked').each(function() { 
		var o = $(this).parent('label').parent('p').parent('div').children('h5').html();
		var v = $(this).parent('label').children('small').html();
		$(this).parent('label').parent('p').parent('div').children('input.olh').val(o + ' ' + v + '\n');
	});
	
	var pages = $('input#Pages').val();
	if (isNaN(pages) || pages == '0' || pages <= '0') {
		$('#Pages').val('1');
	}	
	if (pages > 5) {
		$('#Pages').val('5');
	}
	var price = 77;
//	var price = $('input.baseprice:checked').val();
	var inner = Math.floor(price/2);
	var addons = 0;
	var options = "";
	
	$("input.oh").each(function() {
		var c = $(this).val();
		c = parseInt(c);
		addons += c;
	});
	$("input.olh").each(function() {
		var c = $(this).val();		
		if(c.search(/default/i) == '-1') {
			options += c;
		}
	});

	pages = parseInt(pages);  
	
	var p = parseInt(price);    
	
	var discount = 0;
  var coupon = {FEBRUARY2012: 2};
  $.each( coupon, function(i, v){
   if (i == $('#order-coupon').val()) {
    discount = v;
   }
  });    
	
	var specials = $('input.radio[name=specials]:checked').val();
	switch (specials) {
		case '0': $("#deliver-as").html('XHTML/CSS'); options += 'XHTML/CSS \n'; var days = 1 + ((pages - 1) * 0.5); break;
		case '1': $("#deliver-as").html('WORDPRESS'); options += 'WORDPRESS \n'; var days = 1 + ((pages - 1) * 0.5) + 1; break;
		case '2': $("#deliver-as").html('EMAIL TEMPLATE');  options += 'EMAIL TEMPLATE \n'; var days = 1 + ((pages - 1) * 0.5); break;	
		case '3': $("#deliver-as").html('HTML5/CSS3');  options += 'HTML5/CSS3 \n'; var days = 1 + ((pages - 1) * 0.5); break;	
	}       
	
	var finalprice = p + ((pages - 1) * inner);
	//var days = 1 + ((pages - 1) * 0.5);
	var days = Math.round(days);
	
	var finalprice = Math.floor(finalprice);		
	//if(discount) {
		//discount = Math.round(((finalprice + addons) * discount)/100);
	//}
	var totalprice = finalprice + addons - discount;

	$('span#pages-number').html(pages);
	
	$("#discount").html('$' + discount); 
	$("input[name=discount]").val(discount); 
  //options += 'Coupon Discount: ' + discount + '\n';

	$("#turnaround").html(days + ' WORK DAY'); 
	$("input[name=turnaround]").val(days + ' WORK DAY');     
	//options += 'Turnaround: ' + days + ' WORK DAY \n';

	$('#price em').html('$' + totalprice);
	//options += '$' + totalprice + '\n';  
	$("input[name=Price]").val(totalprice);
	$("input[name=Options]").val(options); 
	
	return true;
}

function validate(form){
	var flag = 1;
	
	$('.row', form).removeClass('row-error');

	$('.notice', form).remove();

	$('.row .req', form).each(function(i){
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if ($(this).hasClass('email') && reg.test($(this).val()) == false) {
			$(this).closest('.row').addClass('row-error');
			flag = 0;
		} else {
			if ($.trim($(this).val())=="") {
				$(this).closest('.row').addClass('row-error');
				flag = 0;
			}
		}
	});

	if(flag) {
		return true;
	}
	else {
		var errorText = '<div class="notice error">Please enter correct values for all red marked fields!</div>';
		$('.row:first', form).before(errorText);      
		return false;
	}

}
function switchTabs(obj){
	$('.tab-content').hide();
	$('.tabs a').removeClass('selected');
	var id = obj.attr('data-tab');
 
	$('#'+id).show();
	obj.addClass('selected');
}
