/* Faux Console by Chris Heilmann http://wait-till-i.com */ 
if(!window.console){
	window.console = {};
	window.console.log = function() {};
	window.console.debug = function() {};
}
String.prototype.trim = function()
{
   return this.replace(/^\s+|\s+$/g,"");
}
/*
$.extend($.ui.accordion.animations, {
  slowbounceslide: function(options) {
    $.ui.accordion.animations.bounceslide(options, { duration: 500 }); }
  });
*/
$.ui.accordion.animations.slowbounceslide = function (a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1E3:400})};

/*
	displaySection function:
	displays a section in the portfolio modal window
*/
function displaySection(section) {
	switch(section) {
	case 'tvAndRadio':
	break;
	default:
	var $itemsWrapper = $('#modalPortfolio .scrollable .items'), $innerWrapper;
	var counter = 1;
	for(var i=1; i < section.size; i++) {
		
		if($.browser.safari && (i-1) % 4 == 0) {
			$innerWrapper = $('<div class="innerWrapper" id="group'+(counter++)+'"/>').appendTo($itemsWrapper);
		}
		
    	var index = (i <= 9) ? '0'+i : i,
    		thumbUrl = 'img/portfolio/'+section.folder+'/'+section.prefix+'_thumb_'+index+'.'+section.ext,
    		thumb = $('<div class="thumb" id="'+index+'"><img src="'+thumbUrl+'"/></div>');
    		$('<div class="ajax-load"></div>').appendTo(thumb).show();
    	
    	thumb.load(function() {
			$('img',this).hide().fadeIn();
			$('.ajax-load',this).hide();
		});
    	thumb.data('img', 'img/portfolio/'+section.folder+'/'+section.prefix+'_'+index+'.'+section.ext);
    	if(typeof section.descriptions[i-1] !== undefined)
    		thumb.data('description', (section.descriptions[i-1] || {}));
    	
    	if($.browser.safari) {
    		$innerWrapper.append(thumb);
    	} else {
    		$itemsWrapper.append(thumb);
    	}
    }
    if(!$.browser.safari) {
	    if(typeof $itemsWrapper.closest('.scrollable').data('scrollable') !== 'undefined')
			$itemsWrapper.closest('.scrollable').data('scrollable').move(0);
		    //$itemsWrapper.closest('.scrollable').scrollable({size: 4});
		    $itemsWrapper.css({left: 0});
    } else {
    	
    }
    break;
    }
}

$('#modalPortfolio div.thumb').live('click', function(e) {
	//Make the current thumbnail active and deactivate all siblings
	$('div.thumb.active').removeClass('active');
	$(e.currentTarget)
		.addClass('active');
	$('#modalPortfolio .ajax-load').show();
	var url = $(e.currentTarget).data('img');
	
	var largeImg = $('<img src="'+url+'"/>').load(function () {
		// set the image hidden by default    
		$(this).hide();
		$('#modalPortfolio .ajax-load').fadeOut();
		// fade our image in to create a nice effect
		$(this).fadeIn();
    });
	
	$('#modalPortfolio div#description').hide().empty()
		.append('<h3 class="title">'+$(e.currentTarget).data('description').title+'</h3>')
		.append('<div class="text">'+$(e.currentTarget).data('description').text+'</div>')
		.fadeIn();
	
	$('#modalPortfolio .container img').remove();
	$('#modalPortfolio .container').append(largeImg);
});

$(function(){
	var userAgent = navigator.userAgent.toLowerCase(); 
	$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); 
	
	// Is this a version of Chrome?
	if($.browser.chrome){
	  userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
	  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
	  $.browser.version = userAgent;
	  // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
	  $.browser.safari = false;
	}
	
	// Is this a version of Safari?
	if($.browser.safari){
	  userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);
	  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
	  $.browser.version = userAgent;
	}
	
	$('#main-wrapper').hide();
	var hasFlash = false;
	try {
	  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
	  if(fo) hasFlash = true;
	}catch(e){
	  if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
	}
	if(!hasFlash) {
		$('#banner').crossSlide({
		  fade: 1
		}, [
		  {
		    src:  'img/bannerslides/slide1.jpg',
		    from: '100% 100% 1x',
		    to:   '50% 50% 1.5x',
		    time: 1
		  }, {
		    src:  'img/bannerslides/slide2.jpg',
		    from: '100% 100% 1x',
		    to:   '50% 50% 1.5x',
		    time: 1
		  }, {
		    src:  'img/bannerslides/slide3.jpg',
		    from: '100% 100% 1x',
		    to:   '50% 50% 1.5x',
		    time: 1
		  }
		]);
	}
	
	/*
		initialize the modalPortfolio
	*/ 
    (function(){
    	var $itemsWrapper = $('#modalPortfolio .scrollable .items');
		var section = portfolio['advertising'];
		displaySection(section);
	    if($.browser.safari) {
	    	$itemsWrapper.find('.innerWrapper').not("#group1").hide();
	    	$itemsWrapper.data("currentGroup", 1);
	    } else {
	   		$itemsWrapper.closest('.scrollable').scrollable({size: 4});
	    }
	    
	    var $firstThumb = $('#modalPortfolio div.thumb').eq(0).addClass('active');
		var largeImg = $('<img style="display:none;" src="'+$firstThumb.data('img')+'"/>');
		
		$('#modalPortfolio div#description')
			.append('<h3 class="title">'+$firstThumb.data('description').title+'</h3>')
			.append('<div class="text">'+$firstThumb.data('description').text+'</div>');
		
		$('#modalPortfolio .container').append(largeImg.fadeIn());
    })();
    
    $('#modalPortfolio a.navigate').click(function() {
    	if($.browser.safari) {
    		var currentGroup = $('#modalPortfolio .scrollable .items').data("currentGroup");
    		var step = ($(this).attr('id') === 'prev') ? (currentGroup == 1) ? 0 : -1 : 1;
    		currentGroup += step;
    		$('#modalPortfolio .items').data("currentGroup", currentGroup);
			$('#modalPortfolio .items #group'+currentGroup).fadeIn().siblings().hide();
    	}
    	else {
    		var step = ($(this).attr('id') === 'prev') ? -4 : 4;
			$('#modalPortfolio .scrollable').data("scrollable").move(step);
		}
	});

	$('#modalPortfolio .arrows').click(function(e) {
		var currentThumb = $('.thumb.active');
		var index = currentThumb.index();
		var thumbsAmt = currentThumb.siblings().length + 1;
		if($(this).hasClass('left')) {
			if($.browser.safari && index == 0) {
	    		var currentGroup = $('#modalPortfolio .scrollable .items').data("currentGroup");
	    		if(currentGroup != 1) {
		    		currentGroup -= 1;
		    		$('#modalPortfolio .items').data("currentGroup", currentGroup);
		    		$('#modalPortfolio .items #group'+currentGroup).fadeIn().siblings().hide()
					$('#modalPortfolio .items #group'+currentGroup).find('.thumb').eq(3).click();
	    		}
			}
			else
				currentThumb.prev().click();
		} else {
			if($.browser.safari && index == (thumbsAmt-1)) {
				var groupAmt =  $('.items .innerWrapper').length;
	    		var currentGroup = $('#modalPortfolio .scrollable .items').data("currentGroup");
	    		if(currentGroup != groupAmt) {
		    		currentGroup += 1;
		    		$('#modalPortfolio .items').data("currentGroup", currentGroup);
					$('#modalPortfolio .items #group'+currentGroup).fadeIn().siblings().hide()
					$('#modalPortfolio .items #group'+currentGroup).find('.thumb').eq(0).click();
				}
			}
			else
				currentThumb.next().click();
		}
		
		
	});
	
	
	$('#modalPortfolio .menu a').click(function(e) {
		if(!$('#fancybox-wrap').is(':visible'))
			return;
		$('#modalPortfolio .menu .active').removeClass('active');
		
		var sectionName = $(e.currentTarget).closest('li').attr('id');
		$('#modalPortfolio li#'+sectionName).addClass('active');
		
		$('div[for=portfolio] .active').removeClass('active');
		$('div[for=portfolio] li#'+sectionName+' a').addClass('active');
		/*
		var section = portfolio[sectionName];
		var $scrollable = $('#modalPortfolio .scrollable').hide();
		//Empty the thumbnail scrollable
		$('.items', $scrollable).empty();
		
		displaySection(section);
		$('#modalPortfolio div.thumb').eq(0).click();
		$('#modalPortfolio .scrollable').fadeIn();
		e.preventDefault();
		*/
	});
	
	
	$('div[for] .menu a').click(function(e) {
		var $menu = $(e.currentTarget).parents('.menu');
		
		$menu.find('a').removeClass('active');
		$menu.find('li').removeClass('active');
		$(e.currentTarget).addClass('active');
		if( $(e.currentTarget).parents('#modalPortfolio').length ) {
			var sectionName = $(e.currentTarget).closest('li').attr('id');
			$('div[for=portfolio] a.active').removeClass('active');
			$('div[for=portfolio] li#'+sectionName+' a').addClass('active');
		} else if( $(e.currentTarget).parents('div[for=portfolio]') ) {
			var sectionName = $(e.currentTarget).closest('li').attr('id');
			$('#modalPortfolio li.active').removeClass('active');
			$('#modalPortfolio').find('li#'+sectionName).addClass('active');
		}
	});

	var styles = {
		'h2#about-us' : "#9b9ca0",
		'h2#capabilities' : "#b5b7b9",
		'h2#our-team' :"#c8c9cb",
		'h2#portfolio' : "#d1d2d3",
		'h2#clients' : "#dddedf",
		'h2#references' : "#eaebec",
		'h2#contact-us' : "#f2f2f3"
	};
	
    $('h2.section')
    .click(function(e) {
    	var $oldActive = $('h2.ui-state-active');
    	var elementColor = styles['h2#'+($oldActive.attr('id'))];
    	$oldActive.animate({backgroundColor: elementColor}, 400);
    	
    	$(e.currentTarget).siblings().find('a').attr("style","");
    	
    	$(e.currentTarget).animate({backgroundColor: 'black'}, 500);
    	$(e.currentTarget).not("#portfolio").next('div').css({ paddingTop: '2em', paddingBottom: '2em'});
    	
    	$('a', e.currentTarget).animate({color: 'white'}, 500);
    	document.location.hash = '#' + $(e.currentTarget).attr('id');
    })
    
    .hover(function(e) {
    	if($(e.currentTarget).hasClass('ui-state-active'))
    		return;
    	$(e.currentTarget).animate({backgroundColor: '#9b9ca0'}, 500);
    	$('a', e.currentTarget).animate({color: 'white'}, 500);
    }, function(e) {
    	if($(e.currentTarget).hasClass('ui-state-active'))
    		return;
		var elementColor = styles['h2#'+($(e.currentTarget).attr('id'))];
    	$(e.currentTarget).animate({backgroundColor: elementColor}, 200);
    	$('a', e.currentTarget).animate({color: 'black'}, 200);
    });
    
    $("#modalPortfolio li.title a").fancybox({
		'titlePosition'		: 'inside',
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'padding'			: 0,
		'modal'				: true,
		'showCloseButton'	: false,
		'overlayOpacity'	: 0.8,
		'overlayColor'		: '#000'
	});
    
	$('#banner').delay(2000).show().slideDown();
	$('#main-wrapper').delay(2000).slideDown();
	
	$('#accordion').accordion({
		header: 'h2', 
		active: false, 
		autoheight: false,
		animated: 'slowbounceslide', 
		collapsible: true,
		clearStyle: true
	});
    
	var scrollToSection = function(value) {
		var section = $('div[for='+value[0]+']');
		if(typeof value[1] === 'undefined' && value[0] !== 'portfolio') {
			$('.menu a', section).eq(0).click();
		}
		switch(value[0]) {
			default:
				if($.address.value() == '/')
					return;
				try {
					var offset = section.find('.container').position().top + section.find('.view div[name='+value[1]+']').position().top,
						easing = (offset < 0) ? 'easeOutBack' : 'easeInBack';
					$('.container', section).animate({
						top: -($('.view', section).find('div[name='+value[1]+']').position().top)
					}, 600, easing);
				} catch(e) {
				
				}
			break;
			case 'clients':
				$('.view .container', section).hide().empty();
				
				if(value[1] == '' || typeof value[1] === 'undefined')
					value[1] = 'fashion';
				
				var $category = $('<div id="'+value[1]+'" class="section letter clearfix">').appendTo($('.view .container', section));
				if(value[1].length == 1) {
					$('<h3 class="title letter">'+value[1]+'</h3>').prependTo($('.view .container', section));
					var letter = value[1];
					var members = "";
					for(var i in clientsList) {
						var membersArray = [];
						
						for(var j in clientsList[i].members) {
							if(letter == clientsList[i].members[j].trim().substring(0,1).toLowerCase())
								membersArray.push(clientsList[i].members[j]);
						}
						//console.log("Members Array: ");
						//console.debug(membersArray);
						if(membersArray.length){
							members += '<div class="category clearfix"><h3 class="title">'+clientsList[i].title+'</h3>\n<div class="column">';
						} else {
							continue;
						}
						var breakIndex = (membersArray.length / 2) | 0, 
							checkIndex = (breakIndex % 2) ? ((membersArray.length == 2) ? 1 : 0) : 1;
						for(var j in membersArray) {
							members += '<div class="client">'+membersArray[j]+'</div>';
							if(j == breakIndex-checkIndex) {
								members += '</div><div class="column">'
							}
						}
						members += '</div></div>';
					}
					$category.append(members);
				} else {
					for(var i in clientsList) {
						if(clientsList[i].category === value[1]) {
							//console.debug(clientsList[i]);
							$category.append('<h3 class="title">'+clientsList[i].title+'</h3>');
							var breakIndex = (clientsList[i].members.length / 3) | 0;
							var members = '<div class="column">';
							for(var j in clientsList[i].members) {
								members += '<div class="client">'+clientsList[i].members[j]+'</div>';
								if(j == breakIndex-1) {
									breakIndex += breakIndex;
									members += '</div><div class="column">';
								}
							}
							members += '</div>';
							$category.append(members);
						}
					}
				}
				$('.view .container', section).fadeIn();
			break;
			case 'references':
				
				if(typeof value[1] === 'undefined')
					value[1] = 'becton';
				
				var index = $('a[href=#references/'+value[1]+']', section).index();
				index = (index <= 9) ? '0'+index : index,
				$('.container', section).hide().empty().append('<img src="img/reference/recommendation_'+index+'.gif" />').fadeIn();
			break;
			case 'portfolio':
				if(typeof value[1] === 'undefined')
					return;
			
				var section = portfolio[value[1]];
				var $scrollable = $('#modalPortfolio .scrollable').hide();
				
				//Empty the thumbnail scrollable
				$('.items', $scrollable).empty();
				
				displaySection(section);
				
				if($.browser.safari) {
			    	$scrollable.find('.innerWrapper').not("#group1").hide();
			    }
				$('#modalPortfolio div.thumb').eq(0).click();
				$('#modalPortfolio .scrollable').fadeIn();
				
				if(!$('#fancybox-wrap').is(':visible')) {
					$('#modalPortfolio li.title a').click();
				}
				
			break;
		}
	};
	// Document title
    var title = document.title;


    // Serialization utility
    var serialize = function(obj, re) {
        var result = [];
        $.each(obj, function(i, val) {
            if ((re && re.test(i)) || !re)
                result.push(i + ': ' + (typeof val == 'object' ? val.join 
                    ? '\'' + val.join(', ') + '\'' : serialize(val) : '\'' + val + '\''));
        });
        return '{' + result.join(', ') + '}';
    };
	
	$.address.init(function(event) {
		/*
        console.debug('init: ' + serialize({
            value: $.address.value(), 
            path: $.address.path(),
            pathNames: $.address.pathNames(),
            parameterNames: $.address.parameterNames(),
            queryString: $.address.queryString()
        }));
        */
        var names = $.map(event.pathNames, function(n) {
            return n.substr(0, 1).toUpperCase() + n.substr(1);
        }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
        var links = names.slice();
        var match = links.length ? links.shift() + ' ' + links.join('.') : 'Home';
        $.address.title([title].concat(names).join(' | '));
        if(typeof event.pathNames[0] !== 'undefined' && event.pathNames.length) {
        	$('h2#'+event.pathNames[0]).click();
        	if(event.pathNames[1].length) {
        		console.log('a[href=#'+$.address.value()+'], '+'div[for='+event.pathNames[0]+']');
        		$('a[href=#'+$.address.value()+']', 'div[for='+event.pathNames[0]+']').click();
        		document.location.hash = '#'+$.address.path();
        	}
        }
    }).change(function(event) {
        //console.debug('change: ' + serialize(event, /parameters|parametersNames|path|pathNames|queryString|value/));
        var names = $.map(event.pathNames, function(n) {
            return n.substr(0, 1).toUpperCase() + n.substr(1);
        }).concat(event.parameters.id ? event.parameters.id.split('.') : []);
        var links = names.slice();
        var match = links.length ? links.shift() + ' ' + links.join('.') : 'Home';
        $.address.title([title].concat(names).join(' | '));
        scrollToSection(event.pathNames);
    });
    
    $.preLoadImages(
     (function() {
     	var array = ['img/modalPortfolio.jpg'];
     	for(var i=1; i<10; i++){
     		array.push('img/reference/recommendation_0'+i+'.gif');
     	}
     	for(var section in portfolio){
     		if(section == 'tvAndRadio')
     			continue;
     		var section = portfolio[section];
     		for(var i=1; i < 4; i++) {
				var index = (i <= 9) ? '0'+i : i;
     			array.push('img/portfolio/'+section.folder+'/'+section.prefix+'_thumb_'+index+'.'+section.ext);
     			array.push('img/portfolio/'+section.folder+'/'+section.prefix+'_'+index+'.'+section.ext);
     		}
     	}
     	array.push('img/reference/recommendation_10.gif');
     	return array;
     })());
    
});


var flashvars = {};
var params = {wmode:"transparent"};
var attributes = {id: "banner2"};

swfobject.embedSWF("logo_animation.swf", "logo", "400", "123", "9.0.0","http://flowplayer.org/swf/expressinstall.swf", flashvars, params, {});
swfobject.embedSWF("slides_animation2.swf", "banner", "900", "340", "9.0.0","http://flowplayer.org/swf/expressinstall.swf", flashvars, params, attributes);


