CFARR = {
	common: {
    init: function() {
    	CFARR.navFade();
    	CFARR.signInSearch();
    }
  },
  
  //search controls
  
  search: {
  	init: function() {},
  	advancedsearch: function() {
  		
  		$('.advanced-search').find('.forms').prepend('<h2>Type of Search</h2><form id="classForm"><p><input class="channel-selector" name="channel" type="radio" value="rugSearchForm"> Rugs <input class="channel-selector" name="channel" type="radio" value="customSearchForm"> Custom</p></form>')
  	
  		$('.channel-selector').click(function() { 
    		var checkedvalue = $(this).val();
    		$('.forms').find('form:not(#'+checkedvalue+')').hide(0);
    		$('#classForm,#'+checkedvalue).show(0);
		});
  	
  	}

  	
  },
  
  //rug controls
  rugs: {
    init: function() {
    
      var $scrollX;
      var $docH = window.innerHeight;
      
      
      $(window).scroll(function(){
      	$scrollX = $(window).scrollTop();
      	//log($scrollX);
      	if ( $docH < ($('#modal').height() + 80) ) {
      		$diff = Math.abs($docH - $('#modal').height());
      		$scrollChange = 40-$scrollX;
      		
      		if ($scrollX < $diff ){
      			log($diff+", "+$scrollChange);
      			$('#modal').css("top", $scrollChange+"px");
      		} else {
      			//log($diff+", "+(($scrollX+40) -$diff));
      			//$('#modal').css("top", ($diff)+"px");
      		}
      		 
      	} else {
      	
      		$('#modal').css("top", ($scrollX+40)+"px");
      	}
      });
    
      $('body').append('<div id="modal-bg" class="loading"><div id="modal-container" class="group"><div id="modal"><div class="close-modal">Close</div><div id="modal-inner"></div></div></div></div>');
      
      $('.close-modal').live('click', function(){
      	
    		$('#modal-bg').fadeOut(500,0, function(){
    			$('.draggable').remove();
    			if( $('#modal-container').hasClass('rug-zoom') ){
    				$('#modal-container').removeClass('rug-zoom');
    			}
    		});
    		
    	});
    	
    },

    view: function() {
      //create view slideshows
      CFARR.slideshow();
      
      var $width;
      
      var newImg = new Image();
      
      
      //capture enquire links and AJAX them
      $('#enquire-link').live('click', function(event){
      	event.preventDefault();
      	var $href = $(this).find('a').attr('href');
      	CFARR.enquire($href);
      });
      
      
      //rug Zoom box feature
      $('#imageBlock').find('a').live('click', function(event){
      	event.preventDefault();
      	var $href = $(this).attr('href');
      	
      	newImg.onload = function() {
    		$height = newImg.height;
    		CFARR.rugZoom($href, $height);
		}
      	
      	newImg.src = $href; // this must be done AFTER setting onload
      	CFARR.rugZoom($href, $height);
      });
      
      
    },
    
    index: function() {
    	
    	
    	$('.collection-list').find('a').click(function(event){
    		event.preventDefault();
    		
    		$docH = $(document).height();
    		var $href = $(this).attr('href');
    		
    		$('#modal-bg').height($docH);
    		
    		$('#modal-inner').load($href + ' #artist', function(){
    			var text = $(this).find('.bio p:first').text().split(' ',30).join(' ');
    			
    			$(this).find('.bio p:first').html(text+'... <a class="more" href="'+$href+'">more &rsaquo;</a>');
    			
    			$(this).find('.bio p:not(:first)').remove();
    			
    			$('#modal-bg').fadeTo(500,1);
    		});
    		
    	});
    
    
    	
    } //end index
    
  },
  
  //custom controls
  
  custom: {
		init: function(){
			var $scrollX;
		      var $docH = window.innerHeight;
		      
		      
		      $(window).scroll(function(){
		      	$scrollX = $(window).scrollTop();
		      	//log($scrollX);
		      	if ( $docH < ($('#modal').height() + 80) ) {
		      		$diff = Math.abs($docH - $('#modal').height());
		      		$scrollChange = 40-$scrollX;
		      		
		      		if ($scrollX < $diff ){
		      			log($diff+", "+$scrollChange);
		      			$('#modal').css("top", $scrollChange+"px");
		      		} else {
		      			//log($diff+", "+(($scrollX+40) -$diff));
		      			//$('#modal').css("top", ($diff)+"px");
		      		}
		      		 
		      	} else {
		      	
		      		$('#modal').css("top", ($scrollX+40)+"px");
		      	}
		      });
		    
		      $('body').append('<div id="modal-bg" class="loading"><div id="modal-container" class="group"><div id="modal"><div class="close-modal">Close</div><div id="modal-inner"></div></div></div></div>');
		      
		      $('.close-modal').live('click', function(){
		      	
		    		$('#modal-bg').fadeOut(500,0, function(){
		    			$('.draggable').remove();
		    			if( $('#modal-container').hasClass('rug-zoom') ){
		    				$('#modal-container').removeClass('rug-zoom');
		    			}
		    		});
		    		
		    	});
		},
	
		view: function(){
			CFARR.caseShow();
			
			$('#enquire-link').live('click', function(event){
		      	event.preventDefault();
		      	var $href = $(this).find('a').attr('href');
		      	CFARR.enquire($href);
		      });
		}
    
  },
  
  //exhibitions controls
  exhibitions: {
		init: function(){
		},
	
		view: function(){
			CFARR.caseShow();
		}
    
  },
  
  //home-two controls
  home2: {
  	init: function(){
  		$('#mainShow').before('<ul id="mainShowNav">').cycle({
				fx: 'scrollLeft',
				speed: '400',
				timeout: 5000,
				pager: '#mainShowNav',
				
			});
  	},
  	index: function(){
  	
  	}
  }
  
}; //end CFARR

UTIL = {
  exec: function( controller, action ) {
    var ns = CFARR,
        action = ( action === undefined ) ? "init" : action;

    if ( controller !== "" && ns[controller] && typeof ns[controller][action] == "function" ) {
      ns[controller][action]();
    }
  },

  init: function() {
    var $body = $('body'),
        controller = $body.data( 'cfarr-controller' ), 
				action = $body.data( 'cfarr-action' );

    UTIL.exec( "common" );
    UTIL.exec( controller );
    UTIL.exec( controller, action );
  }
}; //end UTIL


//common functions
CFARR.slideshow = function(){
	if ($('#imageBlock').find('li').length > 1){
		$('#imageBlock').after('<div id="imageNavBlock"><ul id="imageNav"></ul></div>').find('ul').cycle({
	  	fx: 'fade',
	  	speed:  'fast', 
	    timeout: 0, 
	    pager:  '#imageNav',
	    pagerAnchorBuilder: function(idx, slide) {
	    	var $source = $('#imageBlock').find('li:eq('+idx+')').find('img').data('cfarr-thumb');
	    	return '<li><a href="#"><img src="' + $source + '" /></a></li>'; 
	    }
	  });
  }
}

CFARR.homeshow = function(){
}

CFARR.navFade = function(){
	$('#mainNav li ul').fadeOut(0);
	$('#mainNav li').hover(
		function(){
			$(this).find('a:not(li li a, li form a, .advanced-search)').animate({'color':'rgb(100,100,100)'},200);
			$(this).find('ul').fadeIn(300);
		},function(){
			$(this).find('a:not(li li a)').animate({'color':'rgb(0,0,0)'},200);
			$(this).find('ul').fadeOut(1);
	});
	
	$('#mainNav li li').hover(
		function(){
			$(this).find('a').animate({'color':'rgb(100,100,100)'},200);
		}, function(){
			$(this).find('a').animate({'color':'rgb(200,200,200)'},100);
	});
}

CFARR.signInSearch = function(){
	$('#signInLink, #searchLink').click(function(event){
		event.preventDefault();
		var $link = $($(this).attr('href'));
		var $text = $(this).attr('title');
		
		if ($link.is(':visible')) {
			$link.fadeOut(300);
			$(this).text($text);
			
		} else {
			$link.fadeIn(300);
			$(this).text('Hide');
		}
		
		
	});
}

CFARR.caseShow = function(){
	totalSlides = $('#imageBlock').find('li').length;
	log(totalSlides);
		$('#imageBlock').find('ul')
		.after('<div id="controls"><div id="imageCounter"><span>1</span>/'+totalSlides+'</div><div id="imageControls" class="group"><a id="prevSlide" href="#">Previous</a><a id="nextSlide" href="">Next</a></div></div>')
		.cycle({
			fx: 'fade',
			speed: 'fast',
			timeout: 0,
			next: $('#nextSlide'),
			prev: $('#prevSlide'),
			after:   onAfter
		});
		
		function onAfter(curr, next, opts) {
			var index = opts.currSlide + 1;
			$('#imageCounter').find('span').html(index);
	  }
}

CFARR.enquire = function(href){		
		href = href.replace(/ /g, "%20");
	$('#modal-inner').load(""+href + " #main", function(){
		$imageurl = $('#imageBlock').find('img:first-child').data('cfarr-thumb');
		$('#enquire_img').val($imageurl);
		
		title = $('#modal').find('.page-title').text().replace(/%20/g, ' ');
		$('#modal').find('.page-title').text(title);
		
		$('#modal-bg').fadeTo(500,1);
		
		$('#freeform').submit(function(event) { // bind function to submit event of form
        event.preventDefault();
        $.ajax({
            type: $(this).attr('method'), // get type of request from 'method'
            url: $(this).attr('action'), // get url of request from 'action'
            data: $(this).serialize(), // serialize the form's data
            success: function(responseText) {
                // if everything goes well, update the div with the response
                $('#modal-inner').load("/enquire/thank-you #main");
            }
        });
    });
		
  });

}


CFARR.rugZoom = function(href, maxHeight){
	$docH = $(document).height();
	$windowH = $(window).height();
	$modalW = $('#modal').width();
	$innerW = $('#modal-inner').width();
	
	$modH = $windowH-120;
	
	var $oldValue = $modH;
	var $oldW = 0;
	
	$('#modal-bg').height($docH);
	$('#modal-container').addClass('rug-zoom').height($modH);
	
	$(window).resize(function(){
		$windowH = $(window).height();
		$modH = $windowH-120;
		$('#modal-container').height($modH);
		$modalW = $('#modal').width();
		$innerW = $('#modal-inner').width();
	})
	
	
	
	
	if ($('html').hasClass('touch')){
		
		$('#modal-inner').html('').append('<div class="img touchable"><img id="touchMe" src="'+ href +'"/></div>');
		
		touchGesture.init();
		
		
		$('#modal-bg').fadeTo(500,1, function(){
		
			$imgW = $('.touchable img').width();
			$innerW = $('#modal-inner').width();
			$moveL = ($innerW - $imgW)/2;
	
			$('.touchable').css({'top' : '0px', 'left' : $moveL+'px'});
		
			$('.img.touchable').height($modH);

			$(this).find('.img').fadeTo(250,1);
		});
		
		
		
	} else {
	
		$('#modal-inner').html('').append('<div id="slider-container"><div id="slider"></div></div><div class="img draggable"><img src="'+ href +'"/></div>');
		
		$("#slider").slider({
			orientation: "vertical",
			range: "min",
			min: $modH,
			max: maxHeight,
			value: $modH,
			slide: function( event, ui ) {
				
				$imgH = ui.value;
				$imgW = $('.draggable img').width();
				
				$rate = ($oldValue/$imgH);
				$oldW = $rate*$imgW;
				
				$rateH = ($oldValue-$imgH)/2;
				$rateW = ($oldW-$imgW)/2;
				
				$moveL = ($innerW - $imgW)/2;
				$moveH = ($modH - $imgH)/2;
				
				$('.draggable, .draggable img').height( ui.value );
				
				$top = parseInt($('.draggable').css('top').replace('px',''));	
				$left = parseInt($('.draggable').css('left').replace('px',''));
				
				$topTotal = ($rateH+$top);
				$leftTotal = ($rateW+$left);
				
				$('.draggable').css({'top': $topTotal+'px', 'left': $leftTotal+'px'});
				
				$oldValue = ui.value;
	
			}
		
		
		});
		
		$('#modal-bg').fadeTo(500,1, function(){
		
		$imgW = $('.draggable img').width();
		$innerW = $('#modal-inner').width();
		$moveL = ($innerW - $imgW)/2;

		$('.draggable').css({'top' : '0px', 'left' : $moveL+'px'});
	
	
		$('.img.draggable').height($modH);
		$('.draggable').draggable();
		
		$('.draggable').mousedown(function(){
			$(this).addClass('md');
		});
		
		$('.draggable').mouseup(function(){
			$(this).removeClass('md');
		});
		
		$(this).find('.img').fadeTo(250,1);
	});
	
	
	}
	
	
}

var touchGesture = {

    touchArray: null, //array of elements to be registered with a touch event
    element: null, //the element being touched
    touch: null, //stores the touch information for an element
    //rotation: null, //stores the value of a rotation gesture being performed
    width: null, //stores the width value of an element when performing a gesture
    height: null, //stores the height value of an element when performing a gesture
    startX: null, //stores the starting X coordinates when moving an element
    startY: null, //stores the starting Y coordinates when moving an element
    elementPosX: null, //stores the X coordinate for the center of an element
    elementPosY: null, //stores the Y coordinate for the center of an element
    scale: 1.0, //default scale value for gesture
	
	//function to handle touch events
	handleEvent: function(e) {
		switch(e.type) {
			case 'touchstart': this.onTouchStart(e); break;
			case 'touchmove': this.onTouchMove(e); break;
			case 'touchend': this.onTouchEnd(e); break;
			case 'gesturestart': this.onGestureStart(e); break;
			case 'gesturechange': this.onGestureChange(e); break;
			case 'gestureend': this.onGestureEnd(e); break;
		}
	},

	init: function() { //initialises touch events on elements stored in touchArray.

		this.touchArray = [];	
		this.touchArray = document.querySelectorAll('#touchMe');
  		
  		//for each card, listen for a touchstart event.
		for (var i = 0; i < this.touchArray.length; i++) {
			this.touchArray[i].addEventListener('touchstart', this, false);
            this.touchArray[i].addEventListener('gesturestart', this, false);
  		}	
	},

	onTouchStart: function(e) {
    
        // One finger touch start event
        if(e.touches.length == 1) { 
            e.preventDefault();
            this.element = e.target;
        
            //highlight touched element and change opacity
            this.element.style.opacity = '0.85';
            
            //get the starting coordinates
            this.startX = e.touches[0].clientX;
    		this.startY = e.touches[0].clientY;
    		
            //get the offset center coordinates of the element being touched
    		this.elementPosX = this.element.offsetLeft;
            this.elementPosY = this.element.offsetTop;
        
            //add touchmove and touchend event listeners to the element.
            this.element.addEventListener('touchmove', this, false);
            this.element.addEventListener('touchend', this, false);
        }
	},
	
	onTouchMove: function(e) {
    
        // One finger touch move event
        if(e.touches.length == 1) {
    
            //get the target element of the touch event
            this.element = e.target;
            
            //calculate the distance of the drag
            var leftDelta = e.touches[0].clientX - this.startX;
   			var topDelta = e.touches[0].clientY - this.startY;
            
            //set the position of the element being dragged
            this.element.style.left = (this.elementPosX + leftDelta) + "px";
            this.element.style.top = (this.elementPosY + topDelta) + "px"; 
        }
	},
	
	onTouchEnd: function(e) {
    
		//get the target element of the touch event			
		this.element = e.target;
		
		//remove the highlight colour that was applied on touchstart
		this.element.style.opacity = '1';
        
		//remove touchmove and touchend event listeners.
		this.element.removeEventListener('touchmove', this, false);
		this.element.removeEventListener('touchend', this, false);
		
    },
    
    onGestureStart: function(e) {
    
        //prevent default browser behaviour
        e.preventDefault();
        
        //get the target element of the touch event
        this.element = e.target;
        
        //add a new highlight color for gesture and change opacity
        this.element.style.opacity = '0.85';
        
        //add gesturechange and gestureend event listeners to the element
        this.element.addEventListener('gesturechange', this, false);
        this.element.addEventListener('gestureend', this, false);
    
    },
    
    onGestureChange: function(e) {
    
        //prevent default browser behaviour
        e.preventDefault();
    
        //get the target element of the touch event
        this.element = e.target;
        
        //apply a CSS transformation to the element according to the scale and rotation values of the gesture
        this.element.style.webkitTransform = "scale(" + (this.scale * e.scale) + ")";
    },

    onGestureEnd: function(e) {
    
        //get the target element of the touch event
        this.element = e.target;
        
        //set ighlight colour and opacity back to default state
        this.element.style.opacity = '1';
        
        //store the scale and rotate values should a gesture be performed on the element again
        this.scale *= e.scale;
        //this.rotation = (this.rotation + e.rotation) % 360;
        
        //remove gesturechange and gestureend event listeners
        this.element.removeEventListener('gesturechange', this, false);
        this.element.removeEventListener('gestureend', this, false);
    }
	   
};

$(document).ready( UTIL.init );
