var Categories = {}
var seenItems = null;

if( typeof(PortfolioData) != "undefined"  ) seenItems = new Array( PortfolioData.data.length+1 );


function loadOlderPost(catID){
	var currentCat = getCategoryObject(catID);
	currentCat.offset = parseInt(currentCat.offset) + 1
	setNavDisplay(currentCat)
	
	if(currentCat.offset <  parseInt(currentCat.totalNoOfPosts)){
		loadPost(currentCat)
	}
}

function loadNewerPost(catID){
	var currentCat = getCategoryObject(catID);
	currentCat.offset = parseInt(currentCat.offset) - 1
	setNavDisplay(currentCat)
	if(currentCat.offset >= 0){
		loadPost(currentCat)
	}
}

function loadPost(currentCat){
	loadPostHTML(currentCat.name, currentCat.offset,currentCat.type, "entry"+currentCat.id);
}

function setNavDisplay(currentCat){
	$('navNewer'+currentCat.id).style.display = (currentCat.offset > 0)? "inline":"none"
	$('navOlder'+currentCat.id).style.display = (currentCat.offset == parseInt(currentCat.totalNoOfPosts)-1)?"none":"inline" ;
}

function getCategoryObject(catID){
	return Categories["Category"+catID];
}

function loadPostHTML(categoryName, offset, type, updateDiv){
	
	var url = 'http://test.prettystudio.co.uk/index.php';
	var pars = 'category='+categoryName;
	pars += '&offset='+offset;
	pars += '&type='+type;
	pars += '&isCallBack=true'
	//document.location.href=url+"?"+pars
	var myAjax = new Ajax.Updater(
		updateDiv, 
		url,
		{
			method: 'get', 
			parameters: pars
		});
}

// homepage scripts
var preloadedImages = new Array();
var currentPortfolio;
var currentPortfolioDetails;
var inTransition = false;
var showingDetails = false;
var currentImg;
var justLoadedImage = false;

//init function 
function initPortfolio(){
	Element.hide('count');
	
    Event.observe('portfolioback', 'click', function(e){ Element.hide('portfolioimage');loadNextPortfolio(-1)});
    Event.observe('portfolioforward', 'click', function(e){Element.hide('portfolioimage');loadNextPortfolio(1)});
    Event.observe('portfoliolink', 'click', function(e){loadPortfolio()});
    Event.observe('servicesmore', 'click', function(e){ showServices()});
    Event.observe('servicesless', 'click', function(e){ hideServices()});
    Event.observe('clientsmore', 'click', function(e){showClients()});
    Event.observe('clientsless', 'click', function(e){hideClients()});    
    
    //setup details(not use now)
    //Effect.toggle("portfoliodetails", "blind")
    
    //initialise elements
    $('loadbar1').show();
    $('loadbar2').show();
    $('servicesmore').show();
    $('clientsmore').show(); 
    $('servicesandskillscontent').hide();    
    $('ourclientscontent').hide();        
    $('portfolioback').href = "#previousportfolio";
    $('portfolioforward').href = "#nextportfolio";    

    
    //hide load bars
    new Effect.Scale("loadbar1", 0, {scaleX:true, scaleY:false, duration:0})
    new Effect.Scale("loadbar2", 0, {scaleX:true, scaleY:false, duration:0})
   
    PortfolioData.currentItemID = 0;   
    //setup x/12 display
    setCountDisplay();
        
    //loadNextPortfolio(1);
    Element.show('count');

}

function doNothing() {
}

//change count display
function setCountDisplay(){
	if( typeof( PortfolioData ) != "undefined" )
		$('count').innerHTML = (PortfolioData.currentItemID +1)+"/" + PortfolioData.data.length;
}

//show services box
function showServices(){
    //Effect.BlindDown("servicesandskillscontent", {scaleTo:100});
    Element.show("servicesandskillscontent");

    Element.hide("servicesmore"); 
    Element.show("servicesless");
}

//hide services box
function hideServices(){
    //Effect.BlindUp("servicesandskillscontent");
    Element.hide("servicesandskillscontent");    
    Element.show("servicesmore"); 
    Element.hide("servicesless");    
}

//show clients box
function showClients(){
    //Effect.BlindDown("ourclientscontent", {scaleTo:100});
    Element.show("ourclientscontent");
    Element.hide("clientsmore"); 
    Element.show("clientsless");       
}

//hide clients box
function hideClients(){
    //Effect.BlindUp("ourclientscontent");
    Element.hide("ourclientscontent"); 
    Element.hide("clientsless"); 
    Element.show("clientsmore");     
}

//switch loading... box on/off
function toggleLoading(){
    //$('loading').style.display = ($('loading').style.display  == '' || $('loading').style.display  == 'none')? 'block':'none';
}

//get the current portfolio data
function getCurrentPortfolio(){
     return PortfolioData.data[PortfolioData.currentItemID]
}

//preload images(not used now images are loaded individualy)
function preloadImages(data){
	for(var i = 0; i<data.length; i++){
		var imageName = (i+1) + data[i].name
		if(!preloadedImages[imageName]){
			var oImage = new Image();
			oImage.src = "images/"+imageName+".jpg";
			preloadedImages[i] = oImage;
		}
	}
	
}

//load portfolio page
function loadPortfolio(){
    document.location.href= "portfolio/"+ getCurrentPortfolio().name + ".php"
}

//load next portfolio image
function loadNextPortfolio(direction){//direction either 1 or -1
    //if loading/fading stop action
    
    /* Not needed!!!
    if(inTransition) {
    	return false;
    }
    */
    
    //used to stop any clicks whist working
	inTransition = true; 
    
    //Element.hide('portfolioimage');
    
    //set new portfolio ID
	currentItemID = PortfolioData.currentItemID + direction

    //test boundaries
	if(currentItemID > PortfolioData.data.length - 1)currentItemID = 0;
	if(currentItemID < 0)currentItemID = PortfolioData.data.length - 1;
	
	//save current portfolio ID(this is used to access the data array)
	PortfolioData.currentItemID = currentItemID;
	
	//get the current portolfio
    currentPortfolio = getCurrentPortfolio();	
    
    $("portfolioimagelink").href = "portfolio/" + PortfolioData.data[currentItemID].name + ".php"
	$("portfoliolink").href =  "portfolio/" + PortfolioData.data[currentItemID].name + ".php";        	
	        
    if( seenItems[ currentItemID ] != true ) { 
    	//new Insertion.After('debug', "not seen yet: " + currentItemID + "<br/>" ); 
	
		//get random durations for the load bar expansion
		var duration1 = Math.random(0.1);
		var duration2 = Math.random(0.1);
		
		//expand load bars
		new Effect.Scale("loadbar1", 100, {scaleFrom:0, scaleX:true, scaleY:false, duration:duration1, scaleMode: {originalWidth: 379 }, afterFinish: function(){checkIfLoaded(duration1, duration2)}});
	    new Effect.Scale("loadbar2", 100, {scaleFrom:0, scaleX:true, scaleY:false, duration:duration2, scaleMode: {originalWidth: 379 }, afterFinish: function(){checkIfLoaded(duration2, duration1)}});
	    
	    // set to seen:
	    seenItems[ currentItemID ] = true;
	    
	} else { 
		// load without effect
		checkIfLoaded(0.1, 0.1);
	}
	
	//load the next portfolio images
	loadImage();	
	
	
	//alert("..");
	//use to hide details(not used anymore)
	//if(showingDetails == true)Effect.toggle("portfoliodetails", "blind", {afterFinish: function(){showingDetails = false}})	
}

//check if the image has just loaded(itterative function)
function checkIfLoaded(a, b){
    if(justLoadedImage && a >= b){
        showNextPortfolio();
    }else if(a >= b){		
        setTimeout("checkIfLoaded("+a+","+b+")", 10);
    }
}

//called when the image has loaded and the loadbars have completed
function showNextPortfolio(){	
	
	//loadImage();	
	
    //fade in the images
    new Effect.Appear('portfolioimage', {afterFinish: function(){inTransition = false}, duration:1});      
    
    //hide the load bars
    new Effect.Scale("loadbar1", 0, {scaleX:true, scaleY:false, duration:0})
    new Effect.Scale("loadbar2", 0, {scaleX:true, scaleY:false, duration:0})

  
    //set the text
    var desc = "<span>" + currentPortfolio.description + ": <strong>more...</strong></span>";
    $('portfoliolink').update( desc );                       
    
    //$('projectlink').innerHTML = generatePortfolioLink(); 
    //$('portfolioimage').src = currentImg.src
    
    //reset image load completion var
    justLoadedImage = false;
    
    //hide loading... display
    //toggleLoading();
	
    //set the count display
    setCountDisplay(); 	
	
}

//link to porfolio 
function generatePortfolioLink(){
    return "<strong>more...</strong>";
}

// load a portfolio image
function loadImage(){
	//new Effect.Fade('portfolioimage', {duration:0.3}); 

    var imageFile = currentPortfolio.image;
    currentImg = new Image();
    //toggleLoading();
	$('portfolioimage').style.display = 'none';	
    $('portfolioimage').src = "images/"+imageFile;
    $('portfolioimage').onload = function() {
	   justLoadedImage = true;
    }
}

//show the other porfolio items(not used now)
function loadPortfolioDetails(){
    if(showingDetails == true)return false;
    toggleLoading()
    currentPortfolioDetails = this[getCurrentPortfolio().name + "Data"];
    //keep track of how many images have loaded
    currentPortfolioDetails.noOfLoadedImages = 0
    $('portfoliodetails').innerHTML = "";
    buildPortfolio(currentPortfolioDetails.data)
}

//show the current portfolio, called from the individual portfolio page
function showPortfolio(name){
    
    //get the data
    currentPortfolioDetails = this[name + "Data"];
    
    //reset vars
    currentPortfolioDetails.noOfLoadedImages = 0;
    currentPortfolioDetails.noOfImages = currentPortfolioDetails.data.length;
    
    //start the buuld
    buildPortfolio(currentPortfolioDetails.data)
}

//build the list of portfolio images
function buildPortfolio(data){
    for(var i = 0; i < data.length; i++){
    
        //create containing div
        var section = document.createElement("div");
        section.className = "portfoliodetail";
        
        //create text div
        var info = document.createElement("div");
        info.className = "projectinfo";
        info.style.top = 240+"px";
        
        //create text top line
        var description =  document.createElement("span");
        topline.innerHTML = data[i].description;

        //create text bottom line
        var bottomline = document.createElement("span");
        bottomline.innerHTML = data[i].bottomline;
        
        //build tree
        info.appendChild(topline)
        info.appendChild(bottomline)
        section.appendChild(info);
        
        // create image
        var img = document.createElement("img");   
        img.className = "portfoliodetailsimage";
        img.height = '298';
        img.width = '538';
        img.src = "../images/"+data[i].image;
        img.onload = function()
        {
            //register when image has loaded
            registerImageLoad()
        }        
        
        //add to tree
        section.appendChild(img);    
        
        //add tree to container on page
        var container = $('portfoliodetails');
        container.appendChild(section);
    }
}

/*
function registerImageLoad(){
    currentPortfolioDetails.noOfLoadedImages++
    if(currentPortfolioDetails.noOfLoadedImages == currentPortfolioDetails.data.length){
        toggleLoading()
        Effect.toggle("portfoliodetails", "blind", {afterFinish: function(){showingDetails = true}})
    }
}*/

//record when an image has loaded
function registerImageLoad(){

    //increase count by 1
    currentPortfolioDetails.noOfLoadedImages++
    
    //scale the load bar
    scaleLoadBar()
    
    //if all loaded show the portfolio
    if(currentPortfolioDetails.noOfLoadedImages == currentPortfolioDetails.data.length){
        Effect.BlindDown("portfoliodetails", {duration:3})
        $("loader").style.display = "none"
    }
}

//scale the load bar
function scaleLoadBar(){
    //percentage of total loaded
    var percentage = (currentPortfolioDetails.noOfLoadedImages/currentPortfolioDetails.noOfImages) * 100
    
    //calcs
    var currentWidth = $("loader").getDimensions().width
    var originalWidthvalue = 300;
    var widthPercentage = (currentWidth/originalWidthvalue)*100
    
    //scale
    new Effect.Scale("loader", percentage, {scaleX:true, scaleY:false, duration:1,scaleFrom:widthPercentage ,  scaleMode:{originalWidth: originalWidthvalue}});
}

