var content;
var curentCategory = false;
var curentGallery = false;
var curentPhoto = false;
var curentImages = false;
var loadedImages = ",";
var tmpImg = false;
var height;
var width;

//class is in
var dwProgressBar = new Class({
	
	//implements
	Implements: [Options],

	//options
	options: {
		container: $$('body')[0],
		boxID:'',
		percentageID:'',
		displayID:'',
		startPercentage: 0,
		displayText: false,
		speed:10
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		//create elements
		this.createElements();
	},
	
	//creates the box and percentage elements
	createElements: function() {
		var box = new Element('div', { id:this.options.boxID });
		var perc = new Element('div', { id:this.options.percentageID, 'style':'width:0px;' });
		perc.inject(box);
		box.inject(this.options.container);
		if(this.options.displayText) { 
			var text = new Element('div', { id:this.options.displayID });
			text.inject(this.options.container);
		}
		this.set(this.options.startPercentage);
	},
	
	//calculates width in pixels from percentage
	calculate: function(percentage) {
		return ($(this.options.boxID).getStyle('width').replace('px','') * (percentage / 100)).toInt();
	},
	
	//animates the change in percentage
	animate: function(to) {
		$(this.options.percentageID).set('morph', { duration: this.options.speed, link:'cancel' }).morph({width:this.calculate(to.toInt())});
		if(this.options.displayText) { 
			$(this.options.displayID).set('text', to.toInt() + '%'); 
		}
	},
	
	//sets the percentage from its current state to desired percentage
	set: function(to) {
		this.animate(to);
	}
	
});


function backToPortfolio() {
  $('gallery').innerHTML = '';
  $('portfolio').style.display = '';
}

function openThumbInfo(category, gal) {
var failure = false;
while(failure == false) $try(function() { $('galindex').dispose(); }, function(){ failure = true; });
var temp = new Request({method:"post", url: JSHOMEWWW,  onSuccess: function(response) {
  $('mainImgDiv').innerHTML = $('mainImgDiv').innerHTML + response;
  var morph = new Fx.Morph('galindex');
  morph.start({
    height: height+20 + 'px'
  });
}}).send("page=index&category=" + category + "&gallery=" + gal + "");
}

function openGalleryImg(img) {
  var failure = false;
  while(failure == false) $try(function() { $('galindex').dispose(); }, function(){ failure = true; });
  var openImgMorph = new Fx.Morph('mainImg');
  openImgMorph.start({
		opacity: '0'
	}).chain(function(){
    var myImage = new Asset.image(curentImages[img], {id: 'indexImage', onload: function(){
      height = this.height;
      width = this.width;
    }});
    this.start({
      'background-image': 'url(\'' + curentImages[img] + '\')'
    });
  }).chain(function(){
    this.start({
      opacity: '1',
      width: width + 'px',
  		height: height + 'px'
    });
    $('imgCnt').innerHTML = img+1 + "/" + curentGallery['imgs'].length;
    curentPhoto = img;
  });
}


function openGallery(category, gal) {
  galNum = gal.split("_")[2];
  
  curentGallery = content[category]['galleries'][galNum];
  
  curentImages = new Array();
  i = 0;
  curentGallery['imgs'].each(function(im){
    curentImages[i] = JSHOMEWWW + "/content/img/" + im.img;
    i = i + 1;
  });


  $('portfolio').style.display = 'none';
  var test = new Request({method:"post", url: JSHOMEWWW,  onSuccess: function(response) {
    $('gallery').innerHTML = response;
    
    var pb = new dwProgressBar({
      container: $('prBar'),
      startPercentage: 0,
      speed:1000,
      boxID: 'prBarLine',
      percentageID: 'prBarPerc',
      displayID: 'text'
    });
    
    var myImage = new Asset.image(curentImages[0], {id: 'firstImage', onload: function(){
      height = this.height;
      width = this.width;

      var morph = new Fx.Morph('mainImg');
      morph.start({
  			width: width + 'px',
  			height: height + 'px'
  		});
      var loader = new Asset.images(curentImages, {
        onProgress: function(counter,index) {
          loadedImages = loadedImages + index + ",";
          pb.set((counter + 1) * (100 / curentImages.length));
          $('prBarText').innerHTML = counter+1 + ' of ' + curentImages.length + ' photos loaded'; 
        },
        onComplete: function() {
          var morph = new Fx.Morph('prBar');
          morph.start({
    			  opacity: '0'
    		  });
        }
      });
    }});
    
    var el = $('mainImg');
    curentPhoto = 0;
    
    $('thumbInfo').addEvent('click', function(e){
      e.stop;
      openThumbInfo(category, gal)
    });
    
    var nextPrev;
    
    $('nextImg').addEvent('click', function(e){
      e.stop();
      if( curentGallery['imgs'].length < curentPhoto+1 ) curentPhoto = curentGallery['imgs'].length-2;
       
      if(curentGallery['imgs'].length > curentPhoto+1 && loadedImages.split("," + curentPhoto+1 + ",") != undefined) {
        
        $try(function() { nextPrev.stop; }, function(){  });
        
        nextPrev = new Fx.Morph('mainImg');
    		nextPrev.start({
    			opacity: '0'
    		}).chain(function(){
    		  var myImage = new Asset.image(curentImages[curentPhoto+1], {id: 'indexImage', onload: function(){
            height = this.height;
            width = this.width;
          }});
          this.start({
            'background-image': 'url(\'' + curentImages[curentPhoto+1] + '\')'
          });
        }).chain(function(){
          this.start({
            opacity: '1',
            width: width + 'px',
  		      height: height + 'px'
          });
          $('imgCnt').innerHTML = curentPhoto+2 + "/" + curentGallery['imgs'].length;
          if( curentGallery['imgs'].length < curentPhoto+1 ) curentPhoto = curentGallery['imgs'].length-2;
          else curentPhoto = curentPhoto+1;
        });
    
      }
    });
    $('prevImg').addEvent('click', function(e){
      e.stop;
      
      if( curentPhoto < 0 ) curentPhoto = 1;
      
      if(curentPhoto > 0 && loadedImages.split("," + curentPhoto-1 + ",") != undefined) {
      
        $try(function() { nextPrev.stop; }, function(){  });
        
        nextPrev = new Fx.Morph('mainImg');
        nextPrev.start({
    			opacity: '0'
    		}).chain(function(){
    		  var myImage = new Asset.image(curentImages[curentPhoto-1], {id: 'indexImage', onload: function(){
            height = this.height;
            width = this.width;
          }});
          this.start({
            'background-image': 'url(\'' + curentImages[curentPhoto-1] + '\')'
          });
        }).chain(function(){
          this.start({
            opacity: '1',
            width: width + 'px',
  		      height: height + 'px'
          });
          $('imgCnt').innerHTML = curentPhoto + "/" + curentGallery['imgs'].length;
          if( curentPhoto-1 < 0 ) curentPhoto = 1;
          else curentPhoto = curentPhoto-1;
          
        });
      }
    });
    $('backToPortfolio').addEvent('click', function(){
      backToPortfolio();
      return false;
    });
  }}).send("page=gallery&category=" + category + "&gallery=" + gal + "");
}

window.addEvent('domready', function() {
  if(JSPAGE == 'portfolio') {
    
    var temp = new Request({method:"post", url: JSHOMEWWW,  onSuccess: function(response) {
      
      content = JSON.decode(response);
      var tmpgal;
      
      if(content['series']!=undefined && content['series']['galleries']!=undefined) {
        tmpgal = content['series']['galleries'];
        for( var i=0;i<=tmpgal.length-1;i=i+1) {
          $('portfolio_Series_' + i).addEvent('click', function(){
            openGallery('series', this.id);
            return false;
          });
        }
      }
      
      if(content['editorial']!=undefined && content['editorial']['galleries']!=undefined) {
        tmpgal = content['editorial']['galleries'];
        for( var i=0;i<=tmpgal.length-1;i=i+1) {
          $('portfolio_Editorial_' + i).addEvent('click', function(){
            openGallery('editorial', this.id);
            return false;
          });
        }
      }
      
      if(content['singles']!=undefined && content['singles']['galleries']!=undefined) {
        tmpgal = content['singles']['galleries'];
        for( var i=0;i<=tmpgal.length-1;i=i+1) {
          $('portfolio_Singles_' + i).addEvent('click', function(){
            openGallery('singles', this.id);
            return false;
          });
        }
      }
      
      if(JSCAT != '' && JSGAL != '') {
        openGallery(JSCAT, "1_2_"+JSGAL);
      }
      
    }}).send("page=getcontent");
  }
});