$ = jQuery.noConflict();

$(document).ready(function(){
	initWidget();
	initTeamPager();
	initVacancyPage();
	initContactPage();
	initOrderPage();
	initCommentPage();
	initPostPage();
	initLoginPage();
	initTrackTicketPage();
	initCustomfile();
	initPolls();
	initMainMenu();
	$('#uploadFrame').bind('load', processUploading);	
});

$(window).load(function(){
	initTestimonials();
})

function initPostPage() {
	$('div.wp-caption a').lightbox();
}

function initPolls() {	
	$('#polls input[type=radio]').prettyCheckboxes();
	
	$('#polls li label').hover(
		function () {
    	$(this).animate( { fontSize:"17px", color: "#E5CBA2" } , { queue:false, duration:300 } ); //.animate({color: "#fff"}, {queue:false, duration:300 });
    }, 
    function () {
      $(this).animate( { fontSize:"13px", color: "#E6E2F2" } , { queue:false, duration:300 } ); //.animate({color: "#E6E2F2"}, {queue:false, duration:300 });
    }
	);		
}

function initMainMenu() {	
	$('#main-menu li.last').hover(
		function () {
	  	$(this).children('div.top, ul, div.bottom').css('display', 'block');
	  }, 
	  function () {
	    $(this).children('div.top, ul, div.bottom').css('display', 'none');
	  }
	);	
}

var upload_type = '';

function initWidget(){	
	$('#head-select span').click(function(){		
		widget = $(this).parent().parent();		
		if (widget.attr('class') == ''){
			widget.toggleClass('opened');
			widget.children().children('div.drop-down').slideDown(400);
		} else {
			widget.children().children('div.drop-down').slideUp(400, function() {widget.toggleClass('opened');});
		}
	});
	
	var under_menu = false;
	$('#head-select').mouseover(function(){
		under_menu = true;
	});
	
	$('#head-select').mouseout(function(){		
		widget = $(this);		
		if (widget.hasClass('opened') && widget.children().children('span.jobs').get(0)) {
			under_menu = false;
			setTimeout(function(){							
				if (widget.hasClass('opened') && !under_menu)
					widget.children().children('div.drop-down').slideUp(400, function() {widget.removeClass('opened');});
			}, 1000);
		}
		
	});
	
	
	if ($('#head-select input:file').get(0)){
		
		//init Custom upload box
		filebox = $('#head-select input:file');
		filebox.css('opacity', 0);
		filebox.change(function() {setFilename(this.value, 'input-filename')});
		$('#input-filename').val('');
		
		//submit form
		$('#head-select form').submit(function(){			
			if (!$('#resume-email').val() || $('#resume-email').val() == 'e-mail' || !is_email($('#resume-email').val())) {
				alert('Please enter correct e-mail');
				$('#resume-email').focus();
				return false;
			}
			if (!checkFile($('#head-select input:file').val())){				
				return false;
			}
			//show submit progress
			$('#head-select div.message-box').hide();
			$('#head-select img.ajax-loader-small').show();
			upload_type = 'widget';
		});		
		
		
		
		
		//email box
		$('#resume-email').focus(function(){
			if ($(this).val() == 'e-mail') {
				$(this).val('');
			}
		});
		$('#resume-email').blur(function(){
			if ($(this).val() == '') {
				$(this).val('e-mail');
			}
		});
	}
	
};

function setFilename(fullName, id){	
	shortName = fullName.match(/[^\/\\]+$/);	
	if (id == 'input-filename' || id == 'filelink'){
		$('#'+id).val(shortName);
	} else {		
		document.getElementById(id).innerHTML = shortName;		
	}
	file_name = shortName;
}

function initTeamPager(){
	
	var block_width = 768;
	
	
	if ($('div.team').get(0)) {		
		
	
		photos_num = $('ul.photos li').length;
		pages_num = Math.ceil(photos_num / 4);		 
		pager_html = '';
	
		for (var i=1; i <= pages_num; i++){			
		 
			if (i == 1){
				li_class = 'class="active"';
			} else {
				if (i == 2 || i == 3 ){
					li_class = 'class="one-figure"';
				} else {
					li_class = '';
				}
			}
				
			if (i == 1){
				first_photo_num = 1;
			}else {
				first_photo_num = i*4-4;
			}			
			last_photo_num = i*4;
			
			pager_html += '<li '+li_class+'><a href="#" rel="'+(i-1)+'"><span>'+first_photo_num+'</span><em>'+last_photo_num+'</em></a>';			
			
		}
	
		
		$('div.team div.number ul').html(pager_html);
		
		
		$('div.team div.number ul li a').click(function(){			
			link = $(this);
			$('div.team div.number ul li').removeClass('active');
			link.parent().addClass('active');
			 
			$('ul.photos').animate({ marginLeft: block_width * -1 * link.attr('rel') + 'px'}, 1000, "swing");
			return false;
		});		
	 	 	
	}	
}

function initVacancyPage(){
	if ($('#resume-form').get(0)){
		//init Custom upload box		
		filebox = $('#resume-form input:file');				
		filebox.css('opacity', 0);
		
		//opera hack
		if ($.browser.opera)
			filebox.css('width', '70px');
			
		filebox.change(function(){ setFilename(this.value, 'label-filename') });
		
		
		//name box
		$('#resume-form input[name="candidate[name]"]').focus(function(){
			if ($(this).val() == 'Name') {
				$(this).val('');
			}
		});
		$('#resume-form input[name="candidate[name]"]').blur(function(){
			if ($(this).val() == '') {
				$(this).val('Name');
			}
		});
		
		//phone box
		$('#resume-form input[name="candidate[phone]"]').focus(function(){
			if ($(this).val() == 'Telephone') {
				$(this).val('');
			}
		});
		$('#resume-form input[name="candidate[phone]"]').blur(function(){
			if ($(this).val() == '') {
				$(this).val('Telephone');
			}
		});
		
		//E-mail box
		$('#resume-form input[name="candidate[email]"]').focus(function(){
			if ($(this).val() == 'E-mail') {
				$(this).val('');
			}
		});
		$('#resume-form input[name="candidate[email]"]').blur(function(){
			if ($(this).val() == '') {
				$(this).val('E-mail');
			}
		});
		
		//validate
		$('#resume-form').submit(function(){
			_name =  $('#resume-form input[name="candidate[name]"]');
			email = $('#resume-form input[name="candidate[email]"]');
			phone = $('#resume-form input[name="candidate[phone]"]');			
			_file = $('#resume-form input:file'); 
			
			
						 
			if (!_name.val() || _name.val() == 'Name' ) {
				alert('Please enter your Name');
				_name.focus();
				return false;
			}
	
							
			if (!phone.val() || phone.val() == 'Telephone' || !is_phone(phone.val())) {
				alert('Please enter correct Telephone');
				phone.focus();
				return false;
			}
			
			if (!email.val() || email.val() == 'E-mail' || !is_email(email.val())) {
				alert('Please enter your E-mail');
				email.focus();
				return false;
			}
			
			if (!checkFile(_file.val())){				
				return false;
			}
						
			//show submit progress
			$('div.send-resume div.message-box').hide();
			$('div.send-resume img.ajax-loader').show();
			upload_type = 'form';
		});
	}
}

function initContactPage(){
	if ($('#contact-form').get(0)){
	
		$('textarea.resizable:not(.processed)').TextAreaResizer(); 
	
		//init Custom upload box		
		filebox = $('#contact-form input:file');				
		filebox.css('opacity', 0);
		
		//opera hack
		if ($.browser.opera)
			filebox.css('width', '70px');
			
		filebox.change(function(){ 
			//setFilename(this.value, 'label-filename'); 
			setFilename(this.value, 'filelink'); 
		});
		
		
		//$("#name").DefaultValue('Name');
		//$("#phone").DefaultValue('Telephone');
		//$("#email").DefaultValue('E-mail');
		//$("#company").DefaultValue('Company');
		//$("#comments").DefaultValue('Comments');
		
				
		//validate
		$('#contact-form').submit(function(){
			_name =  $('#name');
			email = $('#email');
			phone = $('#phone');			
			company = $('#company');			
			comments = $('#comments');
						 
			if (!_name.val() || _name.val() == 'Name' ) {
				alert('Please enter your Name');
				_name.focus();
				return false;
			}
			
			if (!email.val() || email.val() == 'E-mail' || !is_email(email.val())) {
				alert('Please enter your E-mail');
				email.focus();
				return false;
			}
			
			if (!company.val() || company.val() == 'Company') {
				company.val('');
				/*alert('Please enter your Company');
				company.focus();
				return false;*/
			}
					
			if (!comments.val() || comments.val() == 'Comments'){
				alert('Please enter your Comment');
				comments.focus();
				return false;
			}	
					
			//show submit progress
			$('div.send-resume div.message-box').hide();
			$('div.send-resume img.ajax-loader').show();
			upload_type = 'form';
		});
	}
}


function initCollapseDescription(){
	var link = $('div.box a.collapse-description');
	link.click(function(e){
		e.preventDefault();
		var box = $('div.box p.description');
		box.slideToggle();
		if ($(this).html() == 'Show Description &gt;&gt;&gt;'){
			$(this).html('Hide Description &lt;&lt;&lt;')
		}	else {
			$(this).html('Show Description &gt;&gt;&gt;');
		}	
	})
}

function initOrderPage(){
	initCollapseDescription();

	if ($('#order-form').get(0)){
	
		$("#deliver_as").selectbox();
		
		$('textarea.resizable:not(.processed)').TextAreaResizer(); 
			
		//init Custom upload box		
		filebox = $('#order-form input:file');				
		filebox.css('opacity', 0);
		
		//opera hack
		if ($.browser.opera)
			filebox.css('width', '70px');
			
		filebox.change(function(){ 
			setFilename(this.value, 'filelink'); 
		});
		
		
		//$("#name").DefaultValue('Name');
		//$("#phone").DefaultValue('Telephone');
		//$("#email").DefaultValue('E-mail');
		//$("#company").DefaultValue('Company');
		//$("#comments").DefaultValue('Comments');
		
				
		//validate
		$('#order-form').submit(function(){
			_name =  $('#name');
			email = $('#email');
			phone = $('#phone');			
			company = $('#company');			
			comments = $('#comments');
						 
			if (!_name.val() || _name.val() == 'Name' ) {
				alert('Please enter your Name');
				_name.focus();
				return false;
			}
			
			if (!email.val() || email.val() == 'E-mail' || !is_email(email.val())) {
				alert('Please enter your E-mail');
				email.focus();
				return false;
			}
			
			if (!company.val() || company.val() == 'Company') {
				company.val('');
				/*alert('Please enter your Company');
				company.focus();
				return false;*/
			}
					
			if (!comments.val() || comments.val() == 'Comments'){
				alert('Please enter your Comment');
				comments.focus();
				return false;
			}	
			$("#implementation").remove();
			var implementation = $("#deliver_as").val()
			$("#deliver_as").before('<input type="hidden" id="implementation" name="implementation" value="'+implementation+'" />');
					
			//show submit progress
			$('div.send-resume div.message-box').hide();
			$('div.send-resume img.ajax-loader').show();
			upload_type = 'form';
		});
	}
}

function initCommentPage(){
	if ($('#commentform').get(0)){		
		
		//name box
		$('#author').focus(function(){
			if ($(this).val() == 'Name') {
				$(this).val('');
			}
		});
		$('#author').blur(function(){
			if ($(this).val() == '') {
				$(this).val('Name');
			}
		});
		
		//email box
		$('#email').focus(function(){
			if ($(this).val() == 'Mail (will not be published)') {
				$(this).val('');
			}
		});
		$('#email').blur(function(){
			if ($(this).val() == '') {
				$(this).val('Mail (will not be published)');
			}
		});
		
		
		//Url box
		$('#url').focus(function(){
			if ($(this).val() == 'Website') {
				$(this).val('');
			}
		});
		$('#url').blur(function(){
			if ($(this).val() == '') {
				$(this).val('Website');
			}
		});
	
		//Clear labeles
		$('#commentform').submit(function(){			
			
			if ($('#author').val() == 'Name') 
				$('#author').val('');
				
			if ($('#email').val() == 'Mail (will not be published)') 
				$('#email').val('');
				
			if ($('#url').val() == 'Website') 
				$('#url').val('');	
		});
		
	}
}

function initLoginPage(){
	if ($('#loginform').get(0)){		
		//login
		//$("#login").DefaultValue("Email");
		//Password
		//$("#password").DefaultValue("Password");
	}
}

function initTrackTicketPage(){
	if ($('#comment-form').get(0)){		
		
		$('textarea.resizable:not(.processed)').TextAreaResizer(); 
		
		//Comment
		//$("#form-comment").DefaultValue("Comment");
		
		
		//init Custom upload box		
		filebox = $('#comment-form input:file');				
		filebox.css('opacity', 0);
		
		//opera hack
		if ($.browser.opera)
			filebox.css('width', '70px');
			
		filebox.change(function(){ 
			setFilename(this.value, 'filelink');
		});
		
		$('#comment-form').submit(function(){
			if ($('#form-comment').val() == 'Comment') 
				$('#form-comment').val('');
		});
		
	}
}

//Uploading
function processUploading(){	
	if(!window.frames['uploadFrame'].document.body.innerHTML)
	  return;
	else{
		var response = window.frames['uploadFrame'].document.body.innerHTML;
		var result = $.evalJSON(response).result;
		var redirect = $.evalJSON(response).redirect;
		var error = '';
		error = $.evalJSON(response).error;
		
		if (result == 'OK'){			
			if (upload_type == 'widget'){
				message = 'Thank you for contacting us.';	
			} else {				
				message = 'Thank you for contacting us.';
			}
			message_class = 'notify';
		} else {			
			if (upload_type == 'widget'){
				message = (error) ? error : 'Please try the another file.';
			} else {				
				message = (error) ? 'Error. ' + error : 'Error uploading file. Please try one more time.';
			}
			message_class = 'error';
		}
		
		if (upload_type == 'widget'){
			$('#head-select img.ajax-loader-small').hide();
			messagebox = $('#head-select div.message-box');
		} else {				
			$('div.send-resume img.ajax-loader').hide();
			messagebox = $('div.send-resume div.message-box');				
		}
		
		messagebox.html(message);
		messagebox.attr('class', 'message-box '+message_class);
		messagebox.css('display', 'inline');
		
		if (upload_type == 'widget' && message_class != 'error'){
			setTimeout(function(){
				widget = $('#head-select');
				widget.children('div.drop-down').slideUp(400, function() {widget.toggleClass('opened');});
			}, 1500);			
		}
		if(redirect != '')
		{
			document.location.href = redirect;
		}
	}
}

function checkFile(value){    
    var file = value;
    extArray = new Array( ".pdf", ".doc", ".odt", ".rtf", ".txt", ".xml", ".ods", ".zip", ".rar" );
    allowSubmit = false;
    
    if (!file) {alert('Please choose resume file'); return false;}
    
    while (file.indexOf("\\") != -1)
    	file = file.slice(file.indexOf("\\") + 1);
    ext = file.slice(file.indexOf(".")).toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
    	if (extArray[i] == ext) { allowSubmit = true; break; }
    }
    if (allowSubmit) 
		return true;
    else
    {
    	alert("Please only upload files that end in types:  "
    	+ (extArray.join("  ")) + "\nPlease select a new "
    	+ "file to upload and submit again.");
    return false;
    }
}


function is_email(address){
	if(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i.test(address)){
		return false;
	} else {
		return true;
	}	
}

function is_phone(number){
	reg = /^[\d\-()\s\+]+$/
	return reg.test(number);
}

/**
 *	testimonials
 */

var testimonialInterval = 10000;
var testimonials = '';
var testimonials_counter = 0;
var testimonials_array = new Array();
  
function initTestimonials(){
	
	if($('#testimonials').get(0)){
		testimonials = setInterval(UpdateTestimonial, testimonialInterval);
	}
	
	//stops switching onhover
	$('#testimonials').hover(
    function () {
     	clearInterval(testimonials);
    }, 
    function () {
      testimonials = setInterval(UpdateTestimonial, testimonialInterval);
    }
  );
}

function UpdateTestimonial(){
	if(testimonials_counter >= 4 )
	{
		//get content from js array
		var randomnumber=Math.floor(Math.random()*5);
		
		var last_testimonial = $.cookie('last_testimonial');
		
		if (isNaN(parseInt(last_testimonial)))
		{
			last_testimonial = 0;
		}
		
		if(randomnumber == last_testimonial)
		{
			randomnumber += 1;
			if(randomnumber >= 5)
			{
				randomnumber = 0;
			}
		}
		
		$.cookie('last_testimonial', randomnumber, {expires: 1});
		
		$('#testimonials').animate(
			{ opacity:0 },
			500, '',
			function(){
				$('#testimonials > div').html(testimonials_array[randomnumber]);
				var newH = $('#testimonials > div').height() + 10;
				$('#testimonials').animate(	{ height: newH, opacity:1 }, 500 );
			}
		);		
	}
	else
	{
		//get json content
		$.getJSON(
			window.location.href + '/testimonial',
			function(data){
				testimonials_array[data['id']-1] = data['html'];
				testimonials_counter += 1;
				//alert(testimonials_counter);
				$('#testimonials').animate(
					{ opacity:0 },
					500, '',
					function(){
						$('#testimonials > div').html(data['html']);
						var newH = $('#testimonials > div').height() + 10;
						$('#testimonials').animate(	{ height: newH, opacity:1 }, 500 );
					}
				);
			}
		);
	}
	
}

file_name = '';

function initCustomfile()
{
	var inputtext;
	var inputfile;
	var browsespace;
		
	var corrections = {x:-50, y:-10};

	if($('div.input-file').get(0)){
	
		inputtext = $('input#filelink');
		//inputtext.attr('readonly', true);
		inputfile = $('div.input-file').find('input.file');
		browsespace = $('div.input-file').find('div.browse');
		
		inputfile.css({
			'opacity':0,
			'position':'absolute',
			'top':corrections.y + 'px',
			'left':corrections.x + 'px',
			'visibility':'visible'
		});
		
		browsespace.mousemove(function(e){
			
			var offset = $(this).offset({ scroll: false });
			var left = (e.pageX - offset.left + corrections.x) * 1;
			var top = (e.pageY - offset.top + corrections.y) * 1;
			inputfile.css({
				'top':top,
				'left':left
			});
		});
		
		$(inputtext).change(function() {		
			if(file_name != ''){
				$(inputtext).val('');
				$(inputfile).val(''); 
				file_name = '';
			}
			else{
				if(!isUrl($(inputtext).val())){
					$(inputtext).val('');
					$(inputfile).val(''); 
				}
			}
		});
	}

}

function isUrl(s) {
	var regexp = new RegExp();
  regexp.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
	return regexp.test(s);
}

function pa( obj )
{
   if(!obj || typeof(obj) != 'object') {
      var _type = typeof(obj);
      if(_type == 'undefined') {
         alert("["+_type+"]");
      }
      else {
         var _output = "[" + _type + "] => `" + obj + "`";
         alert(_output);
      }
      return;
   }
   
   var
      _output = "\t OBJECT PROPERTIES: \n";
      separator = "";
      spacer = "";
      i = 0;
   
   try{
      for( var _key in obj ) {
         if((i % 2) == 1){ separator = "\n"; spacer = "\t\t"; }
         else{ separator = ""; spacer = ""; };
         
         _output += spacer + "[" + _key + '] => `' + obj[_key] + '`' + separator;
         ++i;
      }
   }
   catch(err){
      _output += "Can't get properties for: " + obj;
   }
   
   alert(_output);
} 
