$(document).ready(function(){
  /* vars */
  var bodyId = $('body').attr('id');
  var buyflow = $('div#main div:first').attr('id');
  var stage = document.getElementById('stageapp');
  var runs = 0;
  var Int;
  var alignment;


  /**** functions ****/


  /*** routins **/
  $.localScroll({duration: 1000, easing: 'easeInSine'});

  $(':text:first:not(input#id_order-desired_shipping_date)').focus();

  if ($('.overlay').length > 0){
	$('img.overlay').css({cursor: 'pointer'});
    $('.overlay').overlay();
  };

  /** destroy card **/
  $.fn.destroyCard = function(speed){
    return this.parent('li').parent('ul').parent('div').slideUp(speed, function(){
      $(this).remove();
    });
  };


  /** get preview **/
  $.fn.replace = function($$,url){
    return $$.each(function(){
      $.ajax({
        contentType: 'application/x-javascript-form-urlencoded',
        dataType: 'text',
        timeout: 6000,
        type: 'GET',
        url: url,
        error: function(){
        },
        success: function(data){
          if (data == 'x'){
            runs = runs + 1;
            if (runs == 8){
              $$.addClass('unloadable');
              runs = 0;
              bInt = setInterval(prev, 500);
            }else{
              time = 500 * runs;
              bInt = setInterval(prev, time);
            };
          }else{
            $$.addClass('unloadable');
            bInt = setInterval(prev, 1);
            $$.fadeOut(500, function(){
              $(this).attr({src: data});
            });
            $$.fadeIn(800);
          };
        }
      });
    });
  };


  function prev(){
    clearInterval(bInt);
    $('img[src*="_thumbs/loading_jpg_"]:not(.unloadable):first').each(function(){
      var $$ = $(this);

      if (buyflow == 'basket'){
        var uuid = $$.attr('longdesc').match(/uuid=([a-f0-9-]+)&/)[1];
        var side = $$.attr('longdesc').match(/side=([0-9]+)/)[1];
        var url = '/grusskarten/vorschau/?uuid='+uuid+'&side='+side+'&thumb=60x60';
      } else{
        var url = $$.attr('longdesc');
      };
      $$.replace($$,url);
    });
  };

  if ($('img[src*="_thumbs/loading_jpg_"]:not(.unloadable):first').length > 0){
    bInt = setInterval(prev, 1);
  };

  /* flash notice feedback */
  function flashNotice(){
    $('div.flash_notice').hide();
    $('div.flash_notice').fadeIn(200, function(){
      $(this).children().animate({color: '#ffffc1'}, 750).animate({color: '#cc66cc'}, 1500);
    }).fadeTo(4500, 1.0, function(){
      $(this).fadeOut(1000);
    });
  };

  /* bookmark */
	function bookmark(){
	  $('a.bookmark').click(function(){
	    var link = this;
	    var bookmarkUrl = $(this).attr('href');
      jQuery.ajax({
	      contentType: 'application/x-javascript-form-urlencoded',
	      dataType: 'text',
	      timeout: 1000,
	      type: 'GET',
	      url: bookmarkUrl,
	      error: function(XMLHttpRequest, textStatus, errorThrow){
	      },
	      success: function(data){
	        if (data == 'x'){
	          $(link).addClass('bookmarked');
	        };
	        if (data == 'unx'){
	          $(link).removeClass('bookmarked');
	        };
	        if (data == 'unx_a'){
	          $(link).destroyCard(500);
	        };
	      }
	    });
	    return false;
	  });
	};

  /* stage html link redirect */
  function saveAndRedirect() {
  	stage.saveAndRedirect(url);
  };

  /* flash_notice behaviour */
  flashNotice();

  /* bookmark behaviour */
	bookmark();

	/* stage */
  if (bodyId == 'stage'){
    $('a[href!="#"]').click(function(){
      url = $(this).attr('href');
      saveAndRedirect(url);
      return false;
    });
  };

  /* upload */
  $('form#uploadform').submit(function(){
    $('div#upload_field').children().hide();
    $('div#upload_field').append('<img src="/static/images/ajax-loader.gif" alt="loading" id="upload_loader" style="margin: 30px 135px;" /> <p class="upload_progress">Bitte habe einen Augenblick Geduld, Dein Bild wird gerade hochgeladen.</p>');
  });


  /** buyflow **/
  function formToArray(){
    var a = [];

    var els = $('input:not(:radio, .formsubmit), select, textarea');

    for (var i=0; i < els.length; i++) {
      var el = els[i];

      if ($(el + ':checkbox:not(:checked)').length > 0){

      } else{
        a.push({name: el.name, value: el.value});
      };
    };

    return a;
  };

  function formPost(){
    clearInterval(Int);
    var formArray = formToArray();

    $.ajax({
      contentType: 'application/x-javascript-form-urlencoded',
      dataType: 'text',
      timeout: 3000,
      type: 'POST',
      data: formArray,
      url: window.document.location.href,
      error: function(){
      },
      success: function(data){
        if (data === 'x'){
          alignment = $('div#preview_image img').attr('class');
          Int = setInterval(previewGet, 1000);
        } else{
        };
      },
      complete: function(data){

      }
    });
  };

  function previewGet(){
    clearInterval(Int);
    $.ajax({
      contentType: 'application/x-javascript-form-urlencoded',
      dataType: 'json',
      timeout: 3000,
      type: 'GET',
      url: window.document.location.href + '&c=0',
      error: function(){

      },
      success: function(data){
        var source = data.image.substr(-11);
        var img = $('div#preview_image img');
        if(source.indexOf('loading.jpg') != -1){
          if (img.attr('src').substr(-11) === source){
            $(this).removeAttr('class');
          }else{
            img.animate({opacity: 0}, 500, function(){
              $(this).removeAttr('class').attr({src: data.image, id: data.class_name}).animate({opacity: 1}, 500);
            });
          };
          Int = setInterval(previewGet, 1000);
        }else{
          if ($('div#preview_image img').attr('src').substr(-11) === source){

          }else{
            $('div#preview_image img').animate({opacity: 0}, 1, function(){
              $(this).addClass(data.alignment).attr({src: data.image, id: data.class_name}).animate({opacity: 1}, 1000);
            });
          };
        };
      },
      complete: function(){
      }
    });
  };

  if (buyflow == 'express'){
	  $('div#editor div#preview input.preview').css({display: 'none'});

	  $('div.field:last label').bind('click', function(){

	    var color = $(this).next().attr('value');
	    $('input#id_font_color').attr({value: color});

      /* buyflow change current color selection */
      $('input.color').prev('label').children('img').attr('src', function(){
        return $(this).attr('src').replace(/_a\.gif$/, '.gif');
      });
      $(this).children('img').attr('src', function(){
        return $(this).attr('src').replace(/\.gif$/, '_a.gif');
      });
    });

    /* select current color on page load */
    $('input#id_font_color').each(function(){
      val = $(this).attr('value');
      $('input.color[@value="'+val+'"]').prev('label').click()
    });

	  $('a.preview').bind('click', function(){
	    formPost();

	    return false;
	  });

	  var Int = setInterval(formPost, 1000);
	};

	if (buyflow == 'basket'){
	  /*bInt = setInterval(prev, 1);*/

	  /* datepicker */
    $('input#id_order-desired_shipping_date').date_input();

	  $('td.quantity a.delete').bind('click', function(){
	    if(confirm('Karte wirklich löschen?')){
	      return true;
	    }else{
	      return false;
	    };
	  });
	};

	/* lp - paypal */
	$('img.upload-foto').css({cursor: 'pointer', zIndex: 10000}).click(function(){
	  $.scrollTo('div.block_head:first', 1000);
	});
});
