(function($) {
$.fn.sorted = function(customOptions) {
	var options = {
		reversed: true,
		by: function(a) {return a.text();}
	};
	$.extend(options, customOptions);
	$data = $(this);
	arr = $data.get();
	arr.sort(function(a, b) {
		var valA = parseInt(options.by($(a)));
		var valB = parseInt(options.by($(b)));
		if (options.reversed) {
			return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
		} else {
			return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
		}
	});
	return $(arr);
};
})(jQuery);

var ajaxReq = null;
var $projects;
var $dataProjects;
var loadingTimer;
var withRefreshTypesByClient = false;

function pageload(hash) {
	var controller = hash.split('_');

	if (ajaxReq != null)
		ajaxReq.abort();
	if(controller['0'] == 'strona') {
		ajaxReq = $.ajax({
		  url: "/main/page/home/?id=" + controller['1'],
		  success: function(data) {
			clickToProject();
			isExpanded = !isExpanded;
			if( !isExpanded ) {
				$('#project-details-wrapper').toggle('blind', {}, 500, function(){
					$('#project-details-wrapper').html(data);
					$('#project-details-wrapper').toggle('blind', {}, 500);
				}); 
			} else {
				$('#project-details-wrapper').html(data);				
			}
			
			ajaxReq = null;					

			$('#current_project').show();
			setTimeout( 'doResizeTick()', 550 );			
		  }
		});		
	} else if(controller['0'] == 'project') {
		if( isExpanded ) {
		    setTimeout(
			function() {
			    $('.video-item').each(function(){
				$(this).toggle();
			    });
			     $('#project-details').toggle('blind', {}, 500, function(){
				 ajaxReq = $.ajax({
				      url: "/main/article/home/?id=" + controller['1'],
				      success: function(data) {
					    $('#current_project').html(data);
                                            $('#current_project').show();
					    ajaxReq = null;

					    setTimeout( function(){
						isExpanded = !isExpanded;
						 $('#project-details').toggle('blind', {}, 500, function(){
						      doResizeTick();
                                                      fadeCampaign();                                                      
						     $('.video-item').each(function(){
							 $(this).toggle();
						    } );
						 } );                                                 
                                                createColumns();
						$('#details-plus').toggle();$('#details-minus').toggle();                                                			
						$('html, body').animate({scrollTop:0}, 'slow');
					    }, 700 );
						clickToProject();
				      }
				    });
			     });
			}, 600
		    );
		    
		}
		else {
		    ajaxReq = $.ajax({
		      url: "/main/article/home/?id=" + controller['1'],
		      success: function(data) {                            
			    $('#current_project').html(data);
                            $('#current_project').show();
			    setTimeout( function(){
				isExpanded = !isExpanded;
				 $('#project-details').toggle('blind', {}, 500, function(){
				     doResizeTick();
                                     fadeCampaign();
				     $('.video-item').each(function(){
					 $(this).toggle();
				    } );                                    
				 } );
				$('#details-plus').toggle();$('#details-minus').toggle();                                
                                createColumns();
				$('html, body').animate({scrollTop:0}, 'slow');
				clickToProject();
			    }, 500 );
		      }
		    });
		}

		$('.top_left_menu_item').each(function(){
			$(this).addClass('gray_text');
			var id = $(this).attr('id').replace('_projects','');
			$('#' + id + '_small_icon').attr('src', '/public/images/page/icon_2/' + $('#' + id + '_small_icon').attr('name') + '.png');
		});

		
	} else if(controller['0'] == 'filter') {
                $('#current_project').hide();
		var hash2 = hash.split('strona_');

		if (hash2.length == 2) {
			hash2 = hash2[1]
			$('.select').unselectbox()
			$("#clinets_filter option[value='strona_"+hash2+"']").attr("selected", "selected");
		}

		var hash1 = hash.replace('filter_', '').split('_');

		$('.top_left_menu_item').each(function(){
			$(this).removeClass('gray_text');
			var id = $(this).attr('id').replace('_projects','');
			$('#' + id + '_small_icon').attr('src', '/public/images/page/icon/' + $('#' + id + '_small_icon').attr('name') + '.png');
		});

		for (var i = 0; i < hash1.length; i++) {
			$('#'+hash1[i] +'_projects').addClass('gray_text');
			$('#' + hash1[i] + '_small_icon').attr('src', '/public/images/page/icon_2/' + $('#' + +hash1[i] + '_small_icon').attr('name') + '.png');
		}

		sortProjects();
	}

	createSlectBox();

	return false;
}

function topMenuClick()
{
	var hash  = '';
	$('.top_left_menu_item').each(function(){
		if ($(this).attr('class') == 'Klavika top_left_menu_item gray_text') {
			if($(this).attr('id') != '') {
				hash += $(this).attr('id').replace('projects', '');
			}
		}
	});
        
        //withRefreshTypesByClient = false;
       
	if ($('#clinets_filter').val() != 'all' && $('#clinets_filter').val() != 'null') {
            hash += $('#clinets_filter').val();               
        }

	if (hash != '')
		return '#filter_' + hash;
	else
		return '#filter_';
}

$(function() {	
	$projects = $('#projects_list_ul');
	$dataProjects = $projects.clone();
        $dataProjects.find('li').each(function(){
            $(this).css('display', 'block');
        });
	doResizeTick();
	$.history.init(pageload);
		
        
	$("#contacto").hover(function(){            
            $(this).find('span').css('color', '#d28d48');
            $(this).find('img').attr('src', '/public/images/page/icon/contacto_over.png') ;           
	},function(){            
            $(this).find('span').css('color', '#ffffff'); 
            $(this).find('img').attr('src', '/public/images/page/icon/contacto.png');
	});        
        
        var homeLink = 'filter_';
        
        var href1 = document.location.href.split('#');
        
        if (href1.length == 1) {        
            $('.top_left_menu_item').each(function(){
                homeLink += $(this).attr('id').replace('_projects','') + '_';
            });
            document.location.href = '#' + homeLink;
            $('#current_project').hide();
        }                       
                
	createSlectBox();
	fadeProject();	
	clickToProject();

	$('.top_right_menu_item').unbind('click');
	$('.top_right_menu_item').bind('click',function(){
                $('#current_project').show();
		clickToProject();
		document.location.href = '#' + $(this).attr('href').replace('#','');
	});

	$('.top_left_menu_item').unbind('click');
	$('.top_left_menu_item').bind('click',function(){		
            $('#projects').show();
            if($('#project-details').css('display') != 'none') {
                    $('#project-details').toggle();
                    $('#details-plus').toggle();
                    $('#details-minus').toggle();
            }

		var id = $(this).attr('id').replace('_projects','');

		if($(this).attr('class') == 'Klavika top_left_menu_item') {
			$(this).addClass('gray_text');
			$('#' + id + '_small_icon').attr('src', '/public/images/page/icon_2/' + $('#' + id + '_small_icon').attr('name') + '.png');
		} else {
			$(this).removeClass('gray_text');
			$('#' + id + '_small_icon').attr('src', '/public/images/page/icon/' + $('#' + id + '_small_icon').attr('name') + '.png');
		}
		

		var hash = topMenuClick();
		if(hash != '') {
			document.location.href = hash;
		}		
	});		
});

function createSlectBox() {
	$('.select').unselectbox();
        $('.select').selectbox().unbind('change');
	$('.select').selectbox().bind('change', function(){
                $('#current_project').hide();
                withRefreshTypesByClient = true;
		var hash = topMenuClick();
		if(hash != '')
			document.location.href = hash;
		sortProjects();
	});
}

function sortProjects()
{
	var ids = new Array();
	
	$('.top_left_menu_item').each(function(){
		if ($(this).attr('class') == 'Klavika top_left_menu_item gray_text') {
			if($(this).attr('id').replace('_projects','') != '') {
				ids.push($(this).attr('id').replace('_projects',''));
			}
		}
	});        

	var $filteredData = $dataProjects.find('li');

	var valueA = $('#clinets_filter').val().replace('strona_','').split('_');
	value = valueA[0];                

	if (ids.length) {
		for (i = 0; i < $dataProjects.children().length; i++) {
			$($dataProjects.children()[i]).addClass('get_to_filter');
                        var dataT = $($dataProjects.children()[i]).attr('data-type').split('_');
                        
                        var removeClass = true;
                        
                        for (j = 0; j < dataT.length; j++) {
                            if(ids.join().indexOf(dataT[j]) < 0) {
                                removeClass = false; 
                            }
                        }
                        
                        if (removeClass) {
                            $($dataProjects.children()[i]).removeClass('get_to_filter');
                        }
                        
			if($($dataProjects.children()[i]).attr('data-id2').indexOf(value) < 0 && value != 'all') {
				$($dataProjects.children()[i]).removeClass('get_to_filter');
			}
		}			
	} else {
		for (i = 0; i < $dataProjects.children().length; i++) {
			$($dataProjects.children()[i]).addClass('get_to_filter');
			if($($dataProjects.children()[i]).attr('data-id2').indexOf(value) < 0 && value != 'all') {
				$($dataProjects.children()[i]).removeClass('get_to_filter');
			}
		}
	}	

        if (value !='all' && withRefreshTypesByClient == true) {
            withRefreshTypesByClient = false;
            var filter = '#filter_';
            var itemsTypes = new Array();
            for (i = 0; i < $dataProjects.children().length; i++) {
                $($dataProjects.children()[i]).addClass('get_to_filter');
                if($($dataProjects.children()[i]).attr('data-id2').indexOf(value) < 0 && itemsTypes.indexOf(value) < 0) {
                        $($dataProjects.children()[i]).removeClass('get_to_filter');
                } else {
                    
                    var dataT = $($dataProjects.children()[i]).attr('data-type').split('_');
                    for (j = 0; j < dataT.length; j++) {
                        itemsTypes.push(dataT[j]);
                    }
                }               
            }
                      
            $('.top_left_menu_item').each(function(){
                var idd = $(this).attr('id').replace('_projects','');
                
                if(itemsTypes.indexOf(idd) < 0) {
                    filter += idd + '_';
                }
            });
            
            filter += 'strona_' + valueA.join('_');        
           
            var hh = document.location.href.split('#');
            hh = '#'+hh[1];            

            if (hh != filter)
                document.location.href = filter;
        }
        
        if($dataProjects.find('li.get_to_filter').length == 0) {
            $('#clinets_filter').val('all')
            $('.jquery-selectbox-currentItem').html('muitos clientes');
            createSlectBox();
            for (i = 0; i < $dataProjects.children().length; i++) {
                $($dataProjects.children()[i]).addClass('get_to_filter');
                if($($dataProjects.children()[i]).attr('data-home') != '1') {
                       $($dataProjects.children()[i]).removeClass('get_to_filter');
                }             
            }
            var hh = document.location.href.split('strona');
            
            document.location.href = hh[0];
            
            $('#projects').find('.text_header').html('novos projetos');           
        } else {
            $('#projects').find('.text_header').html('projetos de BRASIL');
        }
        
        $filteredData = $dataProjects.find('li.get_to_filter');

    var $sortedData = $filteredData.sorted({
		by: function(v) {
			return $(v).attr('sort-order');
		}
	});

    $('#projects_list_ul').quicksand($sortedData, {
	duration: 500,
	useScaling : false,
	adjustHeight : 'auto',
	easing: 'swing',
	enhancement: function() {            
		fadeProject();
		clickToProject();
	}

    });
}

function clickToProject() {
	        
	clearInterval(loadingTimer);
	$('.ajax_loader').css('display', 'none');
	$('.campaign_elements_item').unbind('click');
	$('.campaign_elements_item').bind('click',function(){
		var href = document.location.href.split('#');
                $(".project_list_item").unbind('hover');
		if (href[1] != $(this).attr('id').replace('_content','')) {
			$('.campaign_elements_item').unbind('click');
			$(this).find('.ajax_loader').css('display', 'block');
			loadingTimer = setTimeout( "animateLoader('"+$(this).find('.ajax_loader').attr('id')+"', 1)", 100 );
			document.location.href = '#' + $(this).attr('id').replace('_content','');
		}
	});

	clearInterval(loadingTimer);
	$('.project_list_item').unbind('click');
	$('.project_list_item').bind('click',function(){
                $(".project_list_item").unbind('hover');
                $(this).find('.top_left_menu_item_icon_big').hide();
		var href = document.location.href.split('#');
		if (href[1] != $(this).attr('id').replace('_content','')) {
			$('.project_list_item').unbind('click');
			$(this).find('.ajax_loader').css('display', 'block');
			loadingTimer = setTimeout( "animateLoader('"+$(this).find('.ajax_loader').attr('id')+"', 1)", 100 );
			document.location.href= '#' + $(this).attr('id').replace('_content','');
		}
	});
}

function fadeProject()
{
        $(".project_list_item").unbind('hover');
	$(".project_list_item").hover(function(){
            
            var top1 = $(this).position().top + ($(this).height() - $(this).find('.top_left_menu_item_icon_big').height())/2 - 6;
            var left1 = $(this).position().left + ($(this).width() - $(this).find('.top_left_menu_item_icon_big').width())/2;
                                   
            $(this).find('.top_left_menu_item_icon_big').stop(true, true).fadeTo("fast", 1);
            
            $(this).find('.top_left_menu_item_icon_big').css('top',top1);
            $(this).find('.top_left_menu_item_icon_big').css('left',left1);
            
            $(this).find('.project_image').stop(true, true).fadeTo("slow", 0.4);
	},function(){            
            $(this).find('.top_left_menu_item_icon_big').stop(true, true).fadeTo("fast", 0);            
            $(this).find('.project_image').stop(true, true).fadeTo("slow", 1.0);   
	});       
}

function fadeCampaign()
{        
        $(".campaign_elements_item").unbind('hover');
	$(".campaign_elements_item").hover(function(){
            var top1 = $(this).position().top + 30;
            var left1 = $(this).position().left + (140 - $(this).find('div .top_left_menu_item_icon_big').width())/2;
                                   
            $(this).find('div .top_left_menu_item_icon_big').stop(true, true).fadeTo("fast", 1);
            
            $(this).find('div .top_left_menu_item_icon_big').css('top',top1);
            $(this).find('div .top_left_menu_item_icon_big').css('left',left1);
            
            $(this).find('div .project_campaign_image').stop(true, true).fadeTo("slow", 0.4);
	},function(){   
            $(this).find('div .top_left_menu_item_icon_big').stop(true, true).fadeTo("fast", 0);            
            $(this).find('div .project_campaign_image').stop(true, true).fadeTo("slow", 1.0);   
	});     
}

function animateLoader(loader, loop)
{
	var loopName= '';
	if (loop == 13) {loopName = '0px'}
	else {loopName = '-' + (loop * 40) + 'px';}
	$('#' + loader).css( {backgroundPosition: "0px " + loopName} );

	loop = loop + 1;
	loadingTimer = setTimeout( "animateLoader('"+loader+"', "+loop+")", 100 );
}
