if (!window.TOOMANYCOLOURS) {var TOOMANYCOLOURS = { };}


TOOMANYCOLOURS.FUNCTIONS = {
  centNoToEuroStr: function (cents) {
    var euroString = String(Math.round(cents))
    while (euroString.length < 3) {
      euroString = "0" + euroString;
    }
    return euroString.replace(/(\d\d)$/, ",$1") + ' Euro';
  }
};



(function(){
  $(function(){
    initLandingPageIntro();
    
    initFacebookConnect();
    
    initOverlayLogin();
    initDesignStudio();
    initPayPalInfosStudio();
    initPopupWindows();
    initCheckout();

    initColourCard();
		initCopy();
		initCycle();
		initCountDownClock();
		initDesignContestHowTo();
		
		initContestTeaser();
		initMyStudio();
		initPhotosTCswitcher();
		
		initUserPhotoSwitcher();
		
		initClipBoard();
		
		initFancyBox();
		
		$(document.body).ajaxSend(function(evt, request, settings){
			$.jGrowl("LOADING.....");
		});

		$(document.body).ajaxSuccess(function(evt, request, settings){
			$.jGrowl("Done!");
		});
  });

	function initUserPhotoSwitcher(){
		var item = $('.item-image, .visuals');
		
		if (item.length==0) {return};
		
		item.bind('mouseover', function(){
			$(this).children('.user').hide();
			$(this).children('.template').show();
		})
		
		item.bind('mouseout', function(){
			$(this).children('.user').show();			
			$(this).children('.template').hide();
		})
		
	}

	function initFancyBox () {
		jQuery.each($('a.image-with-preview-link'), function() {
		  $(this).fancybox({
		    href: $(this).children('img').attr('src'),
				titleShow: true,
				title: "<a href='" + $(this).attr('href') + "'> Photo Details anschauen</a>"
		  })
		});
		
	};
	
	function initPhotosTCswitcher() {
		if (!$('#new_photo, .formtastic.photo').length){return;};
		
		$('#photo_template_composition_id').change(function(eventObject){
			var $this = $(eventObject.currentTarget)
			
			$.get("/product/t"+$this.val()+'.js', function(data){
				
				var data = eval(data)
				$("#product-preview-image").attr("src", data['template_composition_preview_image']);
				
				var select = $("<select name='photo[composition_id]' id='photo_composition_id'></select>");
				
				if (data.compositions.length>0) {
					$.each(data.compositions, function(i,item){
					  select.append("<option value='"+item.composition['id']+"'>Composition vom "+item.composition.created_at+"</option>");
					});
					if ($('#photo_composition_id_input').length) {
						$('#photo_composition_id').replaceWith(select)
					}else{
						var wrap = $("<li id='photo_composition_id_input' class='select'><label for='photo_composition_id'>Wähle dein Design<abbr title='required'>*</abbr></label></li>");
						$('#photo_template_composition_id_input').after(wrap.append(select));
					};
					
					if (data.compositions.length==1) {
						$.get("/compositions/"+data.compositions[0].composition.id+'.js', function(data){
							var data = eval(data)
							$("#product-preview-image").attr("src", data['preview_image']);
						})
					};
					
				}else{
					if ($('#photo_composition_id_input').length) {
						$('#photo_composition_id_input').remove();
					};
				};
      });
		});
	
		$('#photo_composition_id').live('change', function(eventObject){
			var $this = $(eventObject.currentTarget)
			$.get("/compositions/"+$this.val()+'.js', function(data){
				var data = eval(data)
				$("#product-preview-image").attr("src", data['preview_image']);
			})
		})
	};
	
	
	function initClipBoard() {
		if (!$('#copy-to-clipboard-content').length) {return;};
		var clip = new ZeroClipboard.Client();
		clip.setText($('#copy-to-clipboard-content').val());
		clip.setHandCursor( true );
		clip.glue( 'copy-to-clipboard' );
		
		clip.addEventListener( 'onMouseUp', function(){
			$.jGrowl("Link wurde erfolgreich kopiert.");
		});
		
	};
	
	function initMyStudio() {
		$('li.composition p.hint, li.composition fieldset.inputs').hide();
		
		$('li.composition').mouseenter(function(){
			$(this).find('form.add-to-contest-form').css({position:'absolute'}).end().find('p.hint, fieldset.inputs').slideDown("fast");
		})
		
		$('li.composition').mouseleave(function(){
			$(this).find('p.hint, fieldset.inputs').slideUp("fast");
		})
	};
	
	function initContestTeaser() {
		
		$("textarea#comment_comment, input#comment_name, input#comment_email").defaultvalue();
		
		$('#contest-teaser').animate({ 
			bottom: "-232px"
		}, 500 );
		
		$('.intro').mouseover(function(){
			$("#contest-teaser").stop();
			$('#contest-teaser').animate({ 
				bottom: "-112px"
			}, 500 );
		})
		
		$('.intro').mouseout(function(){
			$("#contest-teaser").stop();
			$('#contest-teaser').animate({ 
				bottom: "-232px"
			}, 500 );
		})
	}
	
	function initCountDownClock(){
		austDay = TOOMANYCOLOURS['endDate'];
		$('#count-down-clock').countdown({
			until: austDay,
			layout: '<span class="days">{dn}<br/><small>{dl}</small></span>' +
							'<span class="hours">{hn}<br/><small>{hl}</small></span>' +
							'<span class="minutes">{mn}<br/><small>{ml}</small></span>' +
							'<span class="seconds">{sn}<br/><small>{sl}</small></span>',
			serverSync: serverTime,
			onExpiry: liftOff
		});
	};
	
	function liftOff() { 
	  window.location = window.location;
	}
	
	function serverTime() { 
		var time = null; 
		$.ajax({url: '/server_time.js', 
			async: false, dataType: 'text', 
			success: function(text) { time = new Date(text);}, 
			error: function(http, message, exc) { time = new Date(); }
		}); 
		return time; 
	}
	
	
	
	function initCycle () {
		$('#composition-preview-image').after('<div id="composition-preview-pager">').cycle({ 
		    speed:  'fast', 
		    timeout: 0, 
		    pager:  '#composition-preview-pager', 
		    pagerAnchorBuilder: function(idx, slide) { 
		      return '<a href="#"><img src="' + slide.src + '" width="50" height="50" /></a>'; 
		    } 
		});
	};
	
	function initCopy() {
		if ($('.copy-to-clipboard').length==0) {return};
		$('.copy-to-clipboard').parent('form').submit(function(event){
			copy($('input.url:eq(0)')[0])
			return false;
		})		
	};
  
	function copy(inElement) {
	  if (inElement.createTextRange) {
	    var range = inElement.createTextRange();
	    if (range && BodyLoaded==1)
	      range.execCommand('Copy');
	  } else {
	    var flashcopier = 'flashcopier';
	    if(!document.getElementById(flashcopier)) {
	      var divholder = document.createElement('div');
	      divholder.id = flashcopier;
	      document.body.appendChild(divholder);
	    }
	    document.getElementById(flashcopier).innerHTML = '';
	    var divinfo = '<embed src="/flash/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	    document.getElementById(flashcopier).innerHTML = divinfo;
	  }
	}

  function initCheckout(){
    // versandkosten observer
    if ( $('.total-with-shipping .popup').length > 0 ) {
      $('.total-with-shipping .popup').qtip({
         content: '<table class="shipping-cost-table"><tbody><tr><td class="country">Deutschland</td><td>' + 
                    TOOMANYCOLOURS.FUNCTIONS.centNoToEuroStr(TOOMANYCOLOURS.STATIC.shippingCostsForCountrys.de) + '</td></tr><tr><td class="country">Österreich</td><td>' + 
                    TOOMANYCOLOURS.FUNCTIONS.centNoToEuroStr(TOOMANYCOLOURS.STATIC.shippingCostsForCountrys.au) + '</td></tr><tr><td class="country">Schweiz</td><td>' + 
                    TOOMANYCOLOURS.FUNCTIONS.centNoToEuroStr(TOOMANYCOLOURS.STATIC.shippingCostsForCountrys.ch) +'</td></tr>'+
                    '<tr><td colspan="2" class="country">Versankostenfrei ab 120 Euro</td><td>' +
                    '</tbody></table>',
         show: 'mouseover',
         hide: 'mouseout'
      })
    }
    
    if ( $('#order_shipping_address_equals_billing_address').length === 0 ) { return; }
    TOOMANYCOLOURS.Checkout.init();
  };
  
  
  function initLandingPageIntro(){
    $("#invitation_email, #invitation_text, #mce-EMAIL").defaultvalue();
		
		$('#landing_page_teaser').cycle({ 
				fx:     'fade',
		    speed:  'slow', 
		    pager:  '#slide-nav',
				delay:  -2000,
				timeout: 8000,
		    pagerAnchorBuilder: function(idx, slide) {
		    	return '#slide-nav li:eq(' + idx + ') a'; 
		    }
		});
		
  }
  
  function initFacebookConnect(){
    if ( window.location.protocol == 'https:' || typeof FB == 'undefined' ) {return;};
    FB.ensureInit(function () {
			TOOMANYCOLOURS.facebookConnect.setup();
      TOOMANYCOLOURS.facebookConnect.createShareLinksForMyStudio();
			TOOMANYCOLOURS.facebookConnect.createShareLinksForContestItem();
    })
  };
  
  function initDesignContestHowTo(){
		var options = {
      width: 831,
      modal: true,
      autoOpen: false,
      position: 'center',
			dialogClass: 'design-contest-how-to-dialog',
			top: 180,
      show: "slide",
      hide: "slide",
      closeOnEscape: true
    }
		var _designContestHowTo = $('#design-contest-how-to').dialog(options);
    
    $('a[href="#design-contest-how-to"]').live('click', function(event){
      _designContestHowTo.dialog('open');
      event.preventDefault();
    })
		
		$('.first-step .product .link').each(function(){
			var $this = $(this);
			$this.text('Wählen')
		})
		
	}
  
	function initOverlayLogin(){
    var options = {
      width: 460,
      modal: true,
      autoOpen: false,
      position: 'top',
      show: "slide",
      hide: "slide",
      closeOnEscape: true
    }
    

    var quickAccountAccessDialog = $('#quick-account-access').dialog(options);
    
    $('a[href="#close-quick-account-dialog"]').live('click', function(){
      quickAccountAccessDialog.dialog( 'close' )
    })
    
    $('a[href="/login"], a[href="/register"]').live('click', function(event){
      var href = $(this).attr('href');
      if (href === '/login') {
        $('#quick-account-access-login').show()
        $('#quick-account-access-register').hide()
      }else if(href === '/register'){
        $('#quick-account-access-login').hide()
        $('#quick-account-access-register').show()
      };
      quickAccountAccessDialog.dialog('open');
      event.preventDefault();
    })
  };
  
  function initDesignStudio(){
    $('#flash_design_studio').each(function() {
      var selectedCompositionId = TOOMANYCOLOURS.STATIC['composition_id'];
      
      var url = '/flash/design_studio.swf';

      var flashvars = {
        compositionId: selectedCompositionId,
        formAuthenticityToken: TOOMANYCOLOURS.STATIC.authenticityToken,
        userIsLoggedIn: TOOMANYCOLOURS.STATIC.userIsLoggedIn,
				currentContest: TOOMANYCOLOURS.STATIC.currentContest,
				userIsParticipating: TOOMANYCOLOURS.STATIC.userIsParticipating
      };

      var params = {
        wmode: 'transparent'
      };
      var attributes = false;

      var width = '968';
      var height = '440';

      swfobject.embedSWF(url, 'flash_design_studio', width, height, '9.0.0', '/flash/expressInstall.swf', flashvars, params, attributes);    
    });
  }
  
  function initPayPalInfosStudio(){
    if ( $('.paypal-information-link').length === 0 ) { return; }
    $('.paypal-information-link').click(function(event){
      window.open('https://www.paypal.com/de/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=500');
      event.preventDefault();
    });
  };
  
  function initPopupWindows(){
    if ( $('a.popup').length === 0 ) { return; }
    $('a.popup').click(function(event){
      var isOpening = TOOMANYCOLOURS.Popup.openUp( $(this) );
      if(isOpening) event.preventDefault();
    })
  };
  
  function initColourCard(){
    TOOMANYCOLOURS.ColourCard.init();
  };
})();