(function() {
  var rt = [];
  hu = window.location.search.substring(1);
  gy = hu.split("&");
  for (i=0;i<gy.length;i++) {
    ft = gy[i].split("=");
    if(ft[0] != "")
      rt.push(ft);
  }
  window.GET = rt;
}());

function getColorImage(color) {
  if(color == "transparent") return color;
  try{
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = 16;
    canvas.height = 16;
    
    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = color;
    ctx.fillRect(0,0,16,16);
    
    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to guess the
    // original format, but be aware the using "image/jpg" will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");
    if(!dataURL)
      dataURL = canvas.toDataURL("image/jpg");
      
    return dataURL;
  }
  catch(e){
    return color;
  }
}

$(document).ready(function(){

  window.store = new Persist.Store('RewardMakerImages');

// Make sure nothing is selected on the form.
//  $("#theform")[0].reset();

  // This function watches for changes on certain elements and applies them to the card.
  var handle_events = function(){
    var my_name = $(this).attr("name");
    var my_value = $(this).val();
    var my_target = $(this).attr("target");
    make_changes(my_name, my_value, my_target);
  };
  var handleRewardCountChange = function(my_name, my_value, my_target){
    var old_count = $(my_target).attr("rewardcount");
    var new_count = parseInt(my_value, 10);
    var diff = Math.abs(old_count-new_count);
    var cloneArmy;
    if(diff == 0) return;
    if(old_count > new_count)
    {
      $(".reward_row", my_target).each(function(){
        $(this).children("td:gt("+(new_count-1)+")").remove();
      });
      $(my_target).attr("rewardcount", new_count);
      
    }else{
      $(".reward_row", my_target).each(function(){
        for(var i=0;i<diff;i++) { 
          $(this).append($(this).children(".reward_level:first").clone(false));
         }
      });
      $(my_target).attr("rewardcount", new_count);
    }
  };
  
  // This applies changes to the card based on element name
  var make_changes = function(my_name, my_value, my_target){
    switch(my_name){
      case "text":
        $(my_target).empty().html(my_value.replace(/\n/g, "<br/>").replace(/\s/g, "&nbsp;"));
        break;
      case "border-radius":
        $(my_target).css("border-radius", my_value); // One day! Right?
        $(my_target).css("-moz-border-radius", my_value);
        $(my_target).css("-webkit-border-radius", my_value);
        break;
      case "cell-count":
        handleRewardCountChange(my_name, my_value, my_target);
        break;
      case "border-spacing":
        if(parseFloat(my_value) <= 0) $(my_target).css("border-collapse", "collapse");
        else if($(my_target).css("border-collapse").toLowerCase() == "collapse") $(my_target).css("border-collapse", "separate");
        $(my_target).css(my_name, my_value);
      break;
      case "inner_img_color":
        var col_img = getColorImage(my_value);
        if(col_img == my_value) {
          $(".inner_image").hide().parent().css("background-color", my_value);
        } else {
          $(".inner_image").attr("src", col_img).show().parent().css("background-color", "transparent");
        }
        break;
      case "border_img_color":
        var col_img = getColorImage(my_value);
        $(".clickable_images>.selected_img").removeClass("selected_img");
        if(col_img == my_value) {
           $(".border_image").hide().parent().css("background-color", my_value);
        } else {
          $(".border_image").attr("src", col_img).show().parent().css("background-color", "transparent");
        }
        break;
      default:
//        console.log(my_name, my_value, my_target)
        $(my_target).css(my_name, my_value);
        break;
    };
  };
  $(".abutton").live("click", handle_events);
  $("select").live("change", handle_events);
  if($.browser.msie) $("select").live("click", handle_events);
  $("input:radio").live("change", handle_events);
  $("input:text").live("keyup", function(){
    var header = $(this).parent().parent().prev().children("a");
    if(header.length==1)
    {
      header.text($(this).val());
    }
    handle_events.call(this);
  });
  
  var loadSavedState = function(){
    store.get("images", function(ok, val) {
      if(ok && val != null){
        var arr = val.split(";");
        for(var i = 0; i < arr.length; i++) {
          var new_img = $('<img alt="" src="uploads/'+arr[i]+'" width="50" height="50" />\n').addClass("droppable").draggable({
            containment:$(".card_display"), 
            opacity:0.666,
            appendTo: ".card",
            helper: "clone"
          });
          $("#my_pictures").append(new_img);
        }
      }
    });
  };    
  loadSavedState();   
  
  
  var sliderHandler = function(append){
    return function(event, ui) {
      var my_name = $(this).attr("name");
      var my_target = $(this).attr("target");
      make_changes(my_name, ui.value+append, my_target);
    };
  };

  var roundEven = function(n){
    var fl = Math.floor(n);
    if(fl % 2 != 0)
      fl++;
    return fl;
  }
  var cloneAndScale2x2Layout = function(){
    for(var i =1; i<=4;i++){
      var clones = $("#thecard_1").children().clone(false);
      $("#thecards_2_"+i).append(clones);
      $("#thecards_2_"+i).css("background-color", $("#thecard_1").css("background-color"));
      $("#thecards_2_"+i+" *").each(function(){
        var l,t,w,h, font, pad;

        // Border image is special because it always stretches to fit
        if($(this).hasClass("border_image")) return;
        if($(this).hasClass("inner_image")) return;
        
        // The card has a padding that must be reduced
        if($(this).hasClass("card")){
          pad = parseFloat($(this).css("padding-top"), 10)/2;
          pad = pad?$(this).css("padding", pad+"px"):"";
        }
        
//        console.log(this.tagName);
        font = parseInt($(this).css("font-size"), 10)/2;
        font = font?$(this).css("font-size", font+"px"):"";
        
        l = roundEven(parseFloat($(this).position().left)/2);
        t = roundEven(parseFloat($(this).position().top)/2);
        w = roundEven(parseFloat($(this).width())/2);
        h = roundEven(parseFloat($(this).height())/2);
        
//        if (this.tagName.toUpperCase() != "TBODY" ) {
          $(this).css("top", t+"px");
          $(this).css("left", l+"px");
//        }

        if (this.tagName.toUpperCase() == "TABLE" ) {
          try{
            $(this).css("border-spacing",  parseFloat($(this).css("border-spacing"))/2+"px");
          }
          catch(e){/* Just ignore it because IE is a little bitch */}
        }

        if (this.tagName.toUpperCase() == "TD" ) {
          $(this).css("border-width", parseFloat($(this).css("border-width"))/2+"px");
          $(this).css("border-radius", parseFloat($(this).css("border-radius"))/2+"px");
          $(this).css("-moz-border-radius", parseFloat($(this).css("-moz-border-radius"))/2+"px");
          $(this).css("-webkit-border-radius", parseFloat($(this).css("-webkit-border-radius"))/2+"px");
        }
        
        if ( $(this).hasClass("title_container") || $(this).hasClass("text_container") || this.tagName.toUpperCase() == "TABLE" ||  this.tagName.toUpperCase() == "TBODY") {
          $(this).css("width", "100%");
        } else if(!$(this).parent().hasClass("text_container") && !$(this).parent().hasClass("title_container") && this.tagName.toUpperCase() != "TR" && ($(this).hasClass("heading_day") || this.tagName.toUpperCase() != "TD") ) {
          $(this).css("width", w+"px");
        }         
        if ( $(this).hasClass("title_container") || $(this).hasClass("text_container") || this.tagName.toUpperCase() == "TABLE" ||  this.tagName.toUpperCase() == "TBODY") {
          $(this).css("height", "100%");
        } else if(!$(this).parent().hasClass("text_container") && !$(this).parent().hasClass("title_container") && this.tagName.toUpperCase() != "TR" && this.tagName.toUpperCase() != "TH"  && this.tagName.toUpperCase() != "TD" ) { 
          $(this).css("height", h+"px");
        }
      });
    }
  };
  var cloneAndScale0x2Layout = function(){
    $("#thecards_2_1").append($('<div style="background-color:white;width:100%;height:100%;"></div>'));
    $("#thecards_2_2").append($('<div style="background-color:white;width:100%;height:100%;"></div>'));
    for(var i=3; i<=4;i++){
      var clones = $("#thecard_1").children().clone(false);
      $("#thecards_2_"+i).css("background-color", $("#thecard_1").css("background-color"));
      $("#thecards_2_"+i).append(clones);
      $("#thecards_2_"+i+" *").each(function(){
        var l,t,w,h, font, pad;

        // Border image is special because it always stretches to fit
        if($(this).hasClass("border_image")) return;
        if($(this).hasClass("inner_image")) return;
        
        // The card has a padding that must be reduced
        if($(this).hasClass("card")){
          pad = parseFloat($(this).css("padding-top"), 10)/2;
          pad = pad?$(this).css("padding", pad+"px"):"";
        }
        
//        console.log(this.tagName);
        font = parseInt($(this).css("font-size"), 10)/2;
        font = font?$(this).css("font-size", font+"px"):"";
        
        l = roundEven(parseFloat($(this).position().left)/2);
        t = roundEven(parseFloat($(this).position().top)/2);
        w = roundEven(parseFloat($(this).width())/2);
        h = roundEven(parseFloat($(this).height())/2);
        
//        if (this.tagName.toUpperCase() != "TBODY" ) {
          $(this).css("top", t+"px");
          $(this).css("left", l+"px");
//        }

        if (this.tagName.toUpperCase() == "TABLE" ) {
          try{
            $(this).css("border-spacing",  parseFloat($(this).css("border-spacing"))/2+"px");
          }
          catch(e){/* Just ignore it because IE is a little bitch */}
        }

        if (this.tagName.toUpperCase() == "TD" ) {
          $(this).css("border-width", parseFloat($(this).css("border-width"))/2+"px");
          $(this).css("border-radius", parseFloat($(this).css("border-radius"))/2+"px");
          $(this).css("-moz-border-radius", parseFloat($(this).css("-moz-border-radius"))/2+"px");
          $(this).css("-webkit-border-radius", parseFloat($(this).css("-webkit-border-radius"))/2+"px");
        }
        
        if ( $(this).hasClass("title_container") || $(this).hasClass("text_container") || this.tagName.toUpperCase() == "TABLE" ||  this.tagName.toUpperCase() == "TBODY") {
          $(this).css("width", "100%");
        } else if(!$(this).parent().hasClass("text_container") && !$(this).parent().hasClass("title_container") && this.tagName.toUpperCase() != "TR" && ($(this).hasClass("heading_day") || this.tagName.toUpperCase() != "TD") ) {
          $(this).css("width", w+"px");
        }         
        if ( $(this).hasClass("title_container") || $(this).hasClass("text_container") || this.tagName.toUpperCase() == "TABLE" ||  this.tagName.toUpperCase() == "TBODY") {
          $(this).css("height", "100%");
        } else if(!$(this).parent().hasClass("text_container") && !$(this).parent().hasClass("title_container") && this.tagName.toUpperCase() != "TR" && this.tagName.toUpperCase() != "TH"  && this.tagName.toUpperCase() != "TD" ) { 
          $(this).css("height", h+"px");
        }
      });
    }
  };
  var col1_s = "rgb(92,92,200)";
  var col2_s = "rgb(200,92,92)";
  var col1_d = getColorImage(col1_s);
  var col2_d = getColorImage(col2_s);
  if(col1_s == col1_d){
    $(".border_image").parent().css('background-color', col1_s);
  }else{
    $(".border_image").show().attr('src', col1_d);
  }
  if(col2_s == col2_d){
    $(".inner_image").parent().css('background-color', col2_s);
  }else{
    $(".inner_image").show().attr('src', col2_d);
  }
//    $("#draggable").draggable();
  $("#draggable").resizable({ghost:true});
  $(".card_display>div>*").css("position", "absolute").draggable({
    cursor: 'move', 
    containment:$(".card_display"), 
 /*   drag: function(event, ui) {
      
    },*/
    opacity:0.666});
    
  $('#output_container').disableSelection();

  $(".reward_table_container").resizable();
    
  $(".draggable_images>img").addClass("droppable").draggable({
    containment:$(".card_display"), 
    opacity:0.666,
    appendTo: "body",
    helper: "clone"
  });

  $(".clickable_images>img").click(function(){
    var $this = $(this);
    var my_src = this.src;
    if($this.hasClass("selected_img")) return;
    $(".clickable_images>.selected_img").removeClass("selected_img");
    $this.addClass("selected_img");
    $(".border_image").attr("src", my_src.replace("thumbs/","")).show().parent().css("background-color", "transparent");
  });

  
  $(".card_display").droppable({
    accept: ".droppable",
    drop: function(e, ui) {
      var posx = 0;
      var posy = 0;
      if (!e) var e = window.event;
      if (e.pageX || e.pageY)   {
        posx = e.pageX;
        posy = e.pageY;
      }
      else if (e.clientX || e.clientY)  {
        posx = e.clientX + document.body.scrollLeft
          + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
          + document.documentElement.scrollTop;
      }
      $(this).find(".placeholder").remove();
      var new_element = ui.draggable.clone();
      new_element.load(function(){
        new_element.css("position", "absolute").removeClass("droppable").removeAttr("width").removeAttr("height");
        var new_container = $('<div class="image_container" style="position:absolute;left:0px;top:0px;"></div>').append(new_element);
        new_container.insertAfter($(".border_image"));

        //we contrain the element to fit within the page
        var wr = Math.min($("body").width()-posx, posx)/(new_element.width()/2);
        var hr = Math.min($("body").height()-posy, posy)/(new_element.height()/2);
        var ratio = wr>hr?hr:wr;
        ratio = Math.min(1, ratio);
        wr = new_element.width() * ratio;
        hr = new_element.height() * ratio;
        new_element.css("width",wr).css("height",hr).css("left",(posx-wr/2)+"px").css("top",(posy-hr/2)+"px");
  
        new_element.dblclick(function(){if(confirm("Are you sure you want to remove this photo from your composition?")){$(this).parents(".image_container").remove();}});
        new_element.resizable({ghost:true});
        new_container.show().children().draggable({cursor: 'move', containment:$(".card_display"), opacity:0.666}).disableSelection();
      });
      // If we don't set the SRC to nothing, IE never loads the new image.
      // I think IE only compares file names and ignores path.
      // Since the two files have the same name, IE thinks we never changed the src attribute.
      var new_loc = new_element[0].src.replace("thumbs/", "");
      new_element[0].src = ""; // Triggers an "error" event cause no image could be found
      new_element[0].src = new_loc;
    }
  });
  /*
      $("#print_2_cards").click(function(){ 
        $("#thecards_2").show();
        cloneAndScale0x2Layout();
        $("#thecard_1").hide();
        window.print(); 
        setTimeout(function(){
          $("#thecard_1").show();
          $("#thecards_2").hide().children().empty();
        }, 10);
      });
      $("#print_2x2").click(function(){ 
        $("#thecards_2").show();
        cloneAndScale2x2Layout();
        $("#thecard_1").hide();
        window.print(); 
        setTimeout(function(){
          $("#thecard_1").show();
          $("#thecards_2").hide().children().empty();
        }, 10);
      });
      $("#print_full").click(function(){ 
        window.print(); 
      });
      */
  $(".accordion").accordion({autoHeight:false});

//    $(".inner_card").sortable();
//    $(".inner_card").disableSelection();
  $("#new_line").click(function(){
    var accordion = $(this).parent().prev().accordion("destroy");
    var count = accordion.children("div").length;
    var new_line = $('<div class="line_'+(count+1)+'" style="font-size:28pt;left:100px;top:50px;font-family:Arial,Arial,Helvetica,sans-serif;">More Text Here</div>');
    var new_line_container = $('<div class="text_container" style="position:absolute;left:0px;top:0px;width:100%"></div>').append(new_line);
    new_line.css("position", "absolute").draggable({cursor:"move", containment:$(".card_display"), opacity:0.666}).disableSelection();
 /*   new_line.dblclick(function(){
      if(confirm("Are you sure you want to remove this line of text from your composition?")){
          $(this).parents(".text_container").remove();
      }
    });*/
    $(".card_display>.title_container").before(new_line_container);
    var heading = $('<h3><a href="#">More Text Here</a></h3>');
    var container = $('<div></div>');
    var title_container = $('<div><label>Text</label></div>')
    title_container.appendTo(container);
    var title = $('<input name="text" target=".line_'+(count+1)+'" type="text" size="40" value="More Text Here"/>')
    title.appendTo(title_container);
    var family_size_container = $('<div><label>Font</label></div>');
    var font_family = $('<select name="font-family" target=".line_'+(count+1)+'" ></select>');
    font_family.appendTo(family_size_container);
    font_family.fontSelector({});
    var size_label = $('<label>&nbsp;Size</label>');
    size_label.appendTo(family_size_container);
    var size = $('<select name="font-size" target=".line_'+(count+1)+'" > <option value="8pt">8pt</option> <option value="10pt">10pt</option> <option value="12pt">12pt</option> <option value="14pt">14pt</option> <option value="16pt">16pt</option> <option value="18pt">18pt</option> <option value="20pt">20pt</option> <option value="24pt">24pt</option> <option selected="selected" value="28pt">28pt</option> <option value="32pt">32pt</option> <option value="36pt">36pt</option> <option value="40pt">40pt</option> <option value="48pt">48pt</option> <option value="56pt">56pt</option> <option value="64pt">64pt</option> <option value="72pt">72pt</option> <option value="80pt">80pt</option> <option value="96pt">96pt</option></select>');
    size.appendTo(family_size_container);
    family_size_container.appendTo(container);
    var colorpicker = $('<div name="color" target=".line_'+(count+1)+'"  class="colorpicker"></div>');
    var colorpicker_container = $('<div><label>Color:</label></div>')
    colorpicker.farbtastic(function(color){
      var my_name = $(this.container).attr("name");
      var my_target = $(this.container).attr("target");
      make_changes(my_name, color, my_target);
    });
    colorpicker_container.appendTo(container);
    colorpicker.appendTo(colorpicker_container);
    // Now header and container contain everything needed for a new 
    accordion.append(heading).append(container).accordion({autoHeight:false});
    accordion.accordion( "option", "active", heading );
  });
  
  $("#panel_right").dialog({
    closeOnEscape: false,
    width:500,
    minWidth:500,
    containment:false,
    autoOpen: false,
    buttons:{
      "Print 2 Cards":function(){ 
			dragonc_print(2);
      }

,


      "Print 2x2":function(){ 
			dragonc_print(4);
      }

,


      "Print Full Page":function(){ 
			dragonc_print(1);
      }


    },
    position:['right','top']
  });
  $("#form_container").tabs();
  $("select[name='font-family']").fontSelector({});
  $('.colorpicker').farbtastic(function(color){
    var my_name = $(this.container).attr("name");
    var my_target = $(this.container).attr("target");
    
    make_changes(my_name, color, my_target);
  });
  

  
  setTimeout(function(){
    $("#panel_right").dialog("open");
    $("#output_container").show();
    $("#loading").fadeOut(500, function(){
      $("body").removeClass("loading-body");
    });
  },0);
});

