var Model = {
	database: [],

	initProfessionalPage: function( json ) {
		this.database = json.data;
	}
};


var Views = {
	
	createTradeShow : function() {
		var tradeshows = Model.database.tradeshows;
		
		var html = ['<ul style="display:none;">'];
		
		for ( x in tradeshows ) {
			var show_date = tradeshows[x].date_date;
			var dateBits = show_date.split('/');
			var display_date = dateBits[1] + '/' + dateBits[0] + '/' + dateBits[2];
			html.push ( '<li><div><div class="tradeshow-show">' , tradeshows[x].show , '</div><p class="tradeshow-details"><span class="trade-show-loation">', tradeshows[x].location , '</span>,<span class="trade-show-date">', display_date , '</span><br />', '<span class="trade-show-contact">Contact:</span> ','<a href="mailto:'+ tradeshows[x].contact__space__mail +'"><span class="trade-show-email">'+ tradeshows[x].contact__space__mail +'</a></span>' , '</p>', '</div></li>' );
		}
		
		html.push('</ul>');
		
		$('#trade-show').append( html.join('') );
	},
	
	createRepresentativesCountry : function() {
		representatives = Model.database.representatives;
		//Create the first level of the slidedown list.
		var html = ['<ul style="display:none;">'];
		var country__slash__area = [];
		
		for ( x in representatives ) {
			//console.log( representatives[x].countryslasharea )
			if( contains( representatives[x].country__slash__area, country__slash__area ) ) {
				continue;
			}
			country__slash__area.push ( representatives[x].country__slash__area );
			
			html.push ( '<li id="' , representatives[x].country__slash__area, '" class="representatives-country" > ' , representatives[x].country__slash__area, '</li>' );
		}
		
		html.push ( '</ul>' );
		
		$('#representatives').append( html.join('') );	
	},
	
	createRepresentativesNames : function( $element ) {

		representatives = Model.database.representatives;
		var html = ['<p style="display:none">'];

		for ( x in representatives ) {
			if ( representatives[x].country__slash__area === $element.attr('id') ) {
				html.push ( '<span class="representitive-name">', representatives[x].name , '</span>' );
				if ( representatives[x].phone != '' ) 
					html.push ('<br /><span class="representitive-phone">' , representatives[x].phone , '</span>');
				if ( representatives[x].email != '' )
					html.push ('<br /><span class="representitive-email">' , representatives[x].email , '</span>');
			}
		}

		html.push ( '</p>' );
	
		$element.append ( html.join('') );
	},
	
	createFranchiseOpportunities : function() {
		
		var franchise = Model.database.franchise;
		
		var html = ['<p style="display:none">' , franchise[0].value , '</p>'];
		$('#franchise-opportunities').append( html.join('') );
	},
	
	//Render the Press Releases on the Press Page.
	showPressReleases : function ( data ) { 
		var html = ['<ul style="display:none">'];
		
		for ( x in data ) {
			if ( data[x].file_file[0] == '/' )
				data[x].file_file = data[x].file_file.substring(1);
				html.push ( '<li><a href="' , data[x].file_file , '" target="_blank">' , data[x].title , '</a></li>' ); 
		}
			
		html.push ( '</ul>' );
		
		$('#press-releases').append( html.join('') );
//		console.log ( data );	
	},

  showLookBook : function ( data ) {
    var html = ['<ul style="display:none">'];

    for ( x in data ) {
      if ( data[x].link[0] == '/' )
        data[x].file_file = data[x].file_file.substring(1);
        html.push ( '<li><a href="' , data[x].link , '" >' , data[x].name , '</a></li>' );
    }

    html.push ( '</ul>' );

		//var html = ['<ul><li><a href="http://kirkoriginals.com/lookbook">Collections Lookbook</a></li><li><a href="http://kirkoriginals.com/lookbooks/vector.pdf">Vector Sunglasses</a></li></ul>'];

    $('#download-loolbook').append( html.join('') );
//    console.log ( data );
  },

	
	showMessage : function ( data , $element ) {
		$element.html( data );
	}

};

var Interactions = {
	
	init : function ()  {
		if($('#download-loolbook').length != 0) {

			AjaxHandlers.getLookBook();

				$('#download-loolbook>a').click( function() {
	
					if( $('#download-loolbook ul').length == 0 || $('#download-loolbook ul').css('display') == 'none' ) {
	
							Interactions.hideSidebarWidgets();

							$('#download-loolbook ul').slideToggle("slow");
					}
					return false;
				});
		}

		
		if ( $('#press-releases a').length != 0) {
			
			AjaxHandlers.getPressReleases();
						
			$('#press-releases>a').click( function() {
				
				if( $('#press-releases ul').length == 0 || $('#press-releases ul').css('display') == 'none' ) {
				
					Interactions.hideSidebarWidgets();
								
					$('#press-releases ul').slideToggle("slow");
				}	
				
				return false;
			});
		}
		
		if ( $('#contact a').length != 0 ) {

			this.enableContactForm();
			
			$('#contact>a').click( function() {
			
				if( $('#div_contact').css('display') == 'none') {
					
					Interactions.hideSidebarWidgets();
					$('#div_contact').slideDown( "slow" );
				}
				
				return false;
				
			});
			
		}
		
		/*
			If true, this is the professional page. Call for the data and set up the Handlers for that page.
		*/
		if ( $('#professional').length != 0 ) {
		
			//Get the data from the server.
			AjaxHandlers.getProfessionalPage();
			
			//Enable Professional Page interactions. 
			this.enableProfessionalPage();
		}
	
	},
	
	/* 
		Interactions for the Professional Page
	*/
	enableProfessionalPage : function () {
		
		$('#representatives').live("click" ,  function() {
			
			if( $('#representatives ul').length == 0 || $('#representatives ul').css('display') == 'none' ) {
				
				Interactions.hideSidebarWidgets();

				//TODO: Change this call. Move it to the load/init space. 				
 				if ( $('#representatives ul').length == 0 ) 
					Views.createRepresentativesCountry();
				
				$('#representatives ul').slideDown();
			}
			
			return false;
		});
		
		$('#representatives li').live ( "click", function() {
			
			//Create the second level of the dropdown list.
			
			if ( $(this).children('p').length == 0 || $(this).children('p').css('display') == 'none' ) {
				
				$('#representatives li p').slideUp();				

 				if ( $(this).children('p').length == 0 ) 				
					Views.createRepresentativesNames( $(this) );
				
				$(this).children('p').slideDown();
				
			}
			
			return false;
						
		});
		
		/*
			Display the Tradeshow Dropdown
		*/
		$('#trade-show').click ( function() {
			
			var isHidden = ( $('#trade-show ul').css('display') == 'none');
			
			if ( $( '#trade-show ul' ).length != 0 && !isHidden  )
				return false;

			Interactions.hideSidebarWidgets();			

			//TODO: Move this call to Init.
			if ( $( '#trade-show ul' ).length == 0 ) {
				Views.createTradeShow();
			}
			
			$(this).children('ul').slideDown( 'slow' );
		});
		
		/*
			Display the Text that is to be associated with Franchise Opportunities
		*/
		$('#franchise-opportunities').click ( function() {
				
			var isHidden = ($('#franchise-opportunities p').css('display') == 'none');
			
			if ( $('#franchise-opportunities p').length != 0 && !isHidden ) {
				return false;
			}
			
			Interactions.hideSidebarWidgets();
			
			//TODO: Move this call to the Init function.
			if ( $('#franchise-opportunities p').length == 0 ) {
				Views.createFranchiseOpportunities();
			}
			
			$('#franchise-opportunities p').slideDown( 'slow' );
		});
		
		/*
			Display the 'form' that is to be shown via the 'Marketing Tools' link
		*/
		$('#marketing-tools').click ( function() {
			var isHidden = ($('#marketing-tools div').css('display') == 'none');
			
			if ( $('#marketing-tools div').length != 0 && !isHidden ) {
				return false;
			}
			
			Interactions.hideSidebarWidgets();
			
			//TODO: Move this call to the Init Function.
			if ( $('#marketing-tools div').length == 0) {
				Views.createMarketingTools();
			}
			
			$('#marketing-tools div').slideDown( 'slow' );
			
		});
		
		/*
			Create the Ajax Call on the click of the Marketing Tools Submit Button!
		*/
		$('#button_marketing_tools').click( function() {
		
			var data = $('#form_marketing_tools').serialize();
			var $element = $('#form_marketing_tools p#message2');
			
			AjaxHandlers.submitMarketingForm( data , $element );
		
			return false;
			
		});
		
		/*
			Change the videos on clicking the link 
		*/
		$('#professional_languages li').live ( "click" ,  function() {
			
			var provideos = Model.database.provideos;
			
			var id = $(this).attr ('id');
			
			for ( x in provideos ) {
				if ( provideos[x].id == id )
					$('#video').html( provideos[x].embed );
			}
			
		});
		
	},
	
	
	initProfessionalPage : function () {
		
		/*
			Populate the languages
		*/
		var data = Model.database.provideos;
		
		var html = ['<ul>'];
		for ( x in data ) {
			
			html.push ( '<li id="' , data[x].id , '">' , data[x].language , '</li>' );
		
		}
		html.push ( '</ul>' );
		
		$('#professional_languages').append ( html.join('') );
		
	},
	
	/*
		Add the interactions for the contact us form. Adds the handlers to enable the form to be submitted.
	*/
	enableContactForm : function () {
		
		$('#button_contact').live("click" , function() {
			
			var data = $('#form_contact').serialize();
			
			var $element = $('#form_contact #message');
			
			AjaxHandlers.submitContactForm ( data , $element );
			
		});
	},
	
	/*
		This function is used to hide all the sidebar widgets. Use it before opening any new widget.
	*/
	hideSidebarWidgets : function() {

		$('.sidebar-item>ul, .sidebar-item>p, .sidebar-item>div, .div_join').slideUp( 'slow' );
		
	}
	
}


var AjaxHandlers = {

	/*
	 Get Press Releases 
	*/
	getPressReleases : function () {
	
		$.ajax ({
			type : "GET" ,
			dataType : "json",
			url : "ajax/getPressReleases" ,
			success : function ( data ) {
							Views.showPressReleases( data );
						},
			complete : function ( data ) {
//							console.log ( 'Completed: ' + this );
						},
			beforeSend : function ( data ) {
//							console.log ( 'Sending: ' + this );
						},
			error : function( XMLHttpRequest , textStatus , errorThrown ) {
							if (console)
								console.log ( textStatus , errorThrown );
						}
		});
		
	},
	
	//Get Look Books

	getLookBook : function () {
		$.ajax ({
			type : "GET" ,
			dataType : "json",
			url : "ajax/getLookBook" ,
			success : function ( data ) {
				Views.showLookBook( data );
			},
			complete : function ( data ) {
			},
			beforeSend : function ( data ) {
			},
			error : function( XMLHttpRequest , textStatus , errorThrown ) {
			}
		});

	},
	/*
		Submit the Contact form and send the emails
	*/
	submitContactForm : function ( data , $element ) {
		
		$.ajax ({
			type : "POST" ,
			data : data,
			dataType : "json",
			url : "ajax/submitContactForm" ,
			success : function ( data ) {
							Views.showMessage ( data.message , $element );
						},
			complete : function ( data ) {
//							console.log ( 'Completed: ' + this );
						},
			beforeSend : function ( data ) {
//							console.log ( 'Sending: ' + this );
						},
			error : function( XMLHttpRequest , textStatus , errorThrown ) {
							if (console)
								console.log ( textStatus , errorThrown );
						}
		});
	
	},
	
	/*
		Get the content that will be used in the Professional Page
	*/
	getProfessionalPage : function ( data , $element ) {
		
		$.ajax ({
			type : "GET" ,
			data : data,
			dataType : "json",
			url : "ajax/getProfessionalPage" ,
			success : function ( data ) {
							//Save the data in the Model.
							Model.initProfessionalPage( data );
							
							//Initialization functions to set up all the data once the model has been populated.
							Interactions.initProfessionalPage();
						},
			complete : function ( data ) {
//							console.log ( 'Completed: ' + this );
						},
			beforeSend : function ( data ) {
//							console.log ( 'Sending: ' + this );
						},
			error : function( XMLHttpRequest , textStatus , errorThrown ) {
							if (console)
								console.log ( textStatus , errorThrown );
						}
		});
		
	},
	
	/*
		Submit the Marketing Contact Form!
	*/
	submitMarketingForm : function ( data , $element ) {
		
		$.ajax ({
			type : "POST" ,
			data : data,
			dataType : "json",
			url : "ajax/submitMarketingForm" ,
			success : function ( data ) {
							Views.showMessage ( data , $element );
						},
			complete : function ( data ) {
						},
			beforeSend : function ( data ) {
						},
			error : function( XMLHttpRequest , textStatus , errorThrown ) {
							if (console)
								console.log ( textStatus , errorThrown );
						}
		});
	
	}

	
}


function contains ( a , obj )  {
	var i = a.length;
	  while (i--) {
		 if (a[i] === obj) {
		   return true;
		 }
	  }
	  return false;
}


/* 
jQuery Fade in Fade out plugin....

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container getâ€™s applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

*/

(function($) {

    $.fn.innerfadeVXT = function(options) {
        return this.each(function() {   
            $.innerfadeVXT(this, options);
        });
    };

    $.innerfadeVXT = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfadeVXT.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfadeVXT.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfadeVXT.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };
		
		$.innerfadeVXT.clickNext = function( container , settings ) {
			var elements = $(container).children();
			var last = last_fade_image;
			var current = current_fade_image;

			$.innerfadeVXT.next (elements , settings, current, last , false );
		};

    $.innerfadeVXT.next = function(elements, settings, current, last , timeouts ) {
				//console.info ( "elements" , elements , "Settings" , settings , "current" ,  current , "last", last );
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
						last_fade_image = last;
						current_fade_image = current;
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						if ( timeouts !== false ) {
	  	      	setTimeout((function() {
 	  	        	$.innerfadeVXT.next(elements, settings, current, last);
 		  	     	}), settings.timeout);
						}
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}


$(document).ready( function () {

	jQuery('#s2').cycle({
    fx:     'fade',
    speed:  'slow',
		fade: 100,
		speedIn: 1000,
		speedOut: 1000,
    timeout: 4000,
    next:   '#next2',
    prev:   '#prev2'
	});


	Interactions.init();
	var fade_options = {
		'animationtype': 'fade',
		'speed': 4000,
		'timeout': 10000,
		'type': 'random',
    'containerheight':  'auto',
    'runningclass':     'innerfade',
    'children':        null
	};
	var current_fade_image = 1;
	var last_fade_image = 0;
	$('#fade-images').innerfadeVXT ( fade_options );
	
	$('#agallery ul li a').hover ( function() {
		if ( $(this).attr('rel').length == 0 ) {
			$(this).attr('rel' , $(this).attr('title' ) );
		}
		$(this).attr('title' , 'Adhip' );
	}, function() {
		$(this).attr('title' , $(this).attr('rel') );

	});
});


