var debug = false;

    var imageSource = '';
    var patternEditorCanvas = new Array();

    var uoploader = null;

    var patternPreset = new Array();
    patternPreset[0] = new Array();
    patternPreset[0][0]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][1]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][2]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][3]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][4]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][5]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][6]=new Array(0,0,0,0,0,0,0,0);
    patternPreset[0][7]=new Array(0,0,0,0,0,0,0,0);

    patternPreset[1] = new Array();
    patternPreset[1][0]=new Array(0,0,0,1,0,0,0,1);
    patternPreset[1][1]=new Array(0,0,1,0,0,0,1,0);
    patternPreset[1][2]=new Array(0,1,0,0,0,1,0,0);
    patternPreset[1][3]=new Array(1,0,0,0,1,0,0,0);
    patternPreset[1][4]=new Array(0,0,0,1,0,0,0,1);
    patternPreset[1][5]=new Array(0,0,1,0,0,0,1,0);
    patternPreset[1][6]=new Array(0,1,0,0,0,1,0,0);
    patternPreset[1][7]=new Array(1,0,0,0,1,0,0,0);

    patternPreset[2] = new Array();
    patternPreset[2][0]=new Array(0,0,0,0,0,0,0,1);
    patternPreset[2][1]=new Array(0,0,0,0,0,0,1,0);
    patternPreset[2][2]=new Array(0,0,0,0,0,1,0,0);
    patternPreset[2][3]=new Array(0,0,0,0,1,0,0,0);
    patternPreset[2][4]=new Array(0,0,0,1,0,0,0,0);
    patternPreset[2][5]=new Array(0,0,1,0,0,0,0,0);
    patternPreset[2][6]=new Array(0,1,0,0,0,0,0,0);
    patternPreset[2][7]=new Array(1,0,0,0,0,0,0,0);

    var params = new Array();
    params["action"] = "ubPreviewNew";

    function loadPattern(index) {
      var pattern = "";
      for (var i = 0; i < 8; ++i) {
        for (var j = 0; j < 8; ++j) {
          pattern += patternPreset[index][i][j];
        }
      }
      return pattern;
    }

    function imageSelectorLoaded() {
      var xsize, ysize, xcut, ycut, rotate;
      var scroller = $(".scroll_image:checked").val();
      if (scroller == 0) {
        xsize = $("#logoSizeX").val();
        ysize = $("#logoSizeY").val();
        xcut = $("#xcut").val();
        ycut = $("#ycut").val();
        rotate = $("#logoRotate").val();
      } else {
        xsize = $("#scrollLogoSizeX").val();
        ysize = $("#scrollLogoSizeY").val();
        xcut = $("#scrollLogoStartBoxX").val();
        ycut = $("#scrollLogoStartBoxY").val();
        rotate = $("#scrollLogoRotate").val();
        $("#scrollLogoSource").val(imageSource);
      }
      var selectionImage = $("#selectionImage").get(0);
      selectionImage.src =  
            '/design/processImage.php?xcut=' + xcut +
            '&ycut=' + ycut +
            '&imageFile=' + imageSource +
            '&xsize=' + xsize +
            '&ysize=' + ysize +
            '&rotate=' + rotate +
            '&action=cut';

      if (($("#logoSizeX").val() > 350) || ($("#logoSizeY").val() > 19)) {
        $("#resize_image_msg").slideDown();
      }
    }

    function backgroundImageLoaded() {
      var selectionImage = $("#selectionImage").get(0);
      var returnedData = selectionImage.contentWindow.dumpImage();
      updateBackgroundData(returnedData);
      loadPreview();
    }

    function updateBackgroundData(inData) {
      $("#logoDump").val(inData);
      $("#scrollOffsets").val('350');
      $("#logoOpacities").val('100');
    }

    function loadPreview() {
      if ($("#userbar_preview").html() != 'loading...') {
        $("#userbar_preview").fadeOut('fast', function() {
            $("#userbar_preview").html('loading...').fadeIn()});
      }
      var scroller = $(".scroll_image:checked").length == 1 ? $(".scroll_image:checked").val() : 
          $("#scroll_image").val();
      $("#elementLayers").val("gradient,pattern,"+(scroller == 0 ? "logo_0" : "scroller")+",text,shine");
      $.post("/design/preview.php", $("#designer_form").serialize(),
        function(data) {
          if (data.status == 'ok') {
            var preview = new Image();
            preview.onload = function() { 
              var src = this.src;
              $("#userbar_preview").fadeOut('fast', function() {
                  $("#userbar_preview").html('<img src="' + src + '" width="350" height="19" alt="" />').fadeIn('medum',
                  function() {
                    var basename = src.substr(src.lastIndexOf('/')+1);
                    $.post("/design/preview.php", 'action=ubDelete&filename=' + basename);
                  });
              });
            };
            preview.src = '/design/imagestor/' + data.image;
            setTimeout('checkPreviewDisplay()', 2000);
          } else {
            $("#userbar_preview").fadeOut('fast', function() {
              $("#userbar_preview").html('preview failed!').fadeIn()});
          }
        }, "json");
    }

    // Sometimes the loadPreview function doesn't work
    // So wait a couple of seconds and check, if it didn't work then retry
    function checkPreviewDisplay() {
      if ($("#userbar_preview").html() == 'loading...') {
        loadPreview();
      }
    }
    
    function setImageDims(inX, inY) {
      var scroller = $(".scroll_image:checked").val();
      if (scroller == 0) {
        $("#logoSizeX").val(inX);
        $("#logoSizeY").val(inY);
      } else {
        $("#scrollLogoSizeX").val(inX);
        $("#scrollLogoSizeY").val(inY);
      }
    }

    function setCuts(inX, inY, inEndX, inEndY) {
      var scroller = $(".scroll_image:checked").val();
      if (scroller == 0) {
        $("#xcut").val(inX);
        $("#ycut").val(inY);
      } else {
        $("#scrollLogoStartBoxX").val(inX);
        $("#scrollLogoStartBoxY").val(inY);
        $("#scrollLogoEndBoxX").val(inEndX);
        $("#scrollLogoEndBoxY").val(inEndY);
      }
    }

if($) {
  $(document).ready(function(){

    var scanlinePatternType = $("#patternType").length == 1 ?
        $("#patternType").val() : ($("input:radio:checked").length == 1 ? $("input:radio:checked").val() : -1); 
    if (scanlinePatternType > -1) $("#pattern").val(loadPattern(scanlinePatternType - 1));

    if ($(".colorpicker").length > 0) {
      $(".colorpicker").jPicker(
        {
          window:
          {
            expandable: true
          },
          images:
          {
            clientPath: '/images/jpicker/' // Path to image files
          }
        },
        function(color, context) {
          var el_id = $(this).attr('id').substr(3);
          var el = $("#" + el_id);
          if (el.length == 1) {
            var all = color.val('all');
            el.val(all ? all.hex : 'none');
if (el_id == "gradientStartColor") {
        $("#gradientStartColor").val(all ? all.hex : 'none');
        loadPreview();
} else if (el_id == "gradientEndColor") {
        $("#gradientEndColor").val(all ? all.hex : 'none');
        loadPreview();
} else if (el_id == "pickedScanlineColor") {
        $("#pickedScanlineColor").val(all ? all.hex : 'none');
        loadPreview();
}
          }
        });
        $.jPicker.List[0].color.active.val('hex', $("#gradientStartColor").val() ? $("#gradientStartColor").val() : null);
        $.jPicker.List[1].color.active.val('hex', $("#gradientEndColor").val() ? $("#gradientEndColor").val() : null);
        $.jPicker.List[2].color.active.val('hex', $("#pickedScanlineColor").val() ? $("#pickedScanlineColor").val() : null);
    }
/*
    if ($("#userbar_upload_image").length == 1) {
            var uploader = new AjaxUpload('userbar_upload_image', {
                action: '/profile/ajax/update_avatar.php',
                name: 'uploadfile',
                autoSubmit: false,
                responseType: false,
                onChange: function(file, ext){
                  $("#edit_avatar_upload_file").val(file);
                  fileSelected = true;
                },
                onSubmit : function(file , ext){
                  $("#editAvatarPopup .infull").fadeOut('fast', function() {
                  $("#editAvatarPopup .infull").html('<div style="text-align:center; margin-top:20px;"><img src="/images/loading-small.gif" width="32" height="32" /></div>').fadeIn()});
                },
                onComplete : function(file, data){
                  data = eval('(' + data + ')');
                  $("#editAvatarPopup .infull").fadeOut('fast', function() {
                  $("#editAvatarPopup .infull").html('<h2 style="text-align:center;">'+data.msg+'</h2>').fadeIn()});
                  if (data.status == 'ok') {
                    if (!data.refreshPage) {
                      $("#baseInfoContainer").fadeOut('fast', function() {
                        $("#baseInfoContainer").html(data.baseInfo).fadeIn()});
                      updateSocnetUrl($("#facebook_url"),
                        data.socnetUrls.facebook_url);
                      updateSocnetUrl($("#twitter_url"),
                        data.socnetUrls.twitter_url);
                      updateSocnetUrl($("#myspace_url"),
                        data.socnetUrls.myspace_url);
                    }
                  }
                  window.setTimeout(function() { data.refreshPage ? window.location.reload() : $.fancybox.close(); }, 3000);
                }
            });
    }
*/
    $("#text, #totalScrollFrames, #scrollLogoDelay").change(function() {
      loadPreview();
    });

    $("input:radio").click(function() {
      var el = $(this);
      var id = el.attr("id");
      var val = el.val();
      if (id.substr(0, 29) == "userbar_scanline_pattern_type") {
        $("#pattern").val(loadPattern(id.substr(30) - 1));
        loadPreview();
      } else if (id.substr(0, 14) == "scrollLogoEOA_") {
        loadPreview();
      }
    });

    $(".set_form_action").livequery("click", function() {
      $("#designer_form").attr("action", $(this).attr("href"));
      $("#designer_form").submit();

      return false;
    });

    $("a#confirm_finished").fancybox({
        'onComplete' : function() {
            $("#generateType").val("final");
            $.post("/design/preview.php", $("#designer_form").serialize(),
              function(data){
                if (data.status == 'ok') {
                  window.location = '/design/finished.php?nubid=' + data.id +
                      '&dyn=' + data.dynamic;
                } else {
                  $("#confirmFinished .infull").fadeOut('fast', function() {
                    $("#confirmFinished .infull").html('<h2 style="text-align:center;">Failed</h2>').fadeIn()});
                  window.setTimeout(function() { $.fancybox.close(); }, 3000);
                }
              }, "json");
      }
    });

    $('#inplaceSignupForm').livequery("keyup", function(e){
      if (e.which == 13) {
         $('#btnInplaceSignupSubmit').click();
       }
      return false;
    });

    $("#userbar_fetch_image_button").livequery("click", function() {
      if (($("#userbar_fetch_image").val() != '') &&
          ($("#userbar_fetch_image").val() != 'http://www.yoursite.com/yourimage')) {
        $("#graphic_work_space").slideDown();
        selectSourceImage($("#userbar_fetch_image").val());
      }

      return false;
    });

    if ($("#userbar_upload_image:visible").length == 1) {
      $('#userbar_upload_image_button').livequery("click", function(e){
        if (uploader) {
          uploader.submit();
        }
        return false;
      });

      var fileSelected = false;
      uploader = new AjaxUpload('userbar_upload_image', {
          action: '/design/uploadSourceImage.php',
          name:'upload',
          autoSubmit: false,
          responseType: false,
          onChange: function(file, ext){
            $("#userbar_upload_image").val(file);
            fileSelected = true;
          },
          onSubmit : function(file , ext){
//            $("#editAvatarPopup .infull").fadeOut('fast', function() {
//            $("#editAvatarPopup .infull").html('<div style="text-align:center; margin-top:20px;"><img src="/images/loading-small.gif" width="32" height="32" /></div>').fadeIn()});
          },
          onComplete : function(file, data) {
            data = eval('(' + data + ')');
            if (data.status == 'ok') {
              $("#userbar_upload_image_fullpath").val(data.file);
              selectSourceImage(data.file);
            } else {
//alert(data.msg);
            }
          }
      });
    }

    function selectSourceImage(source) {
      imageSource = source;
      $("#graphic_work_space").slideDown();
      var scroller = $(".scroll_image:checked").val();
      var attrSrc;
      if (scroller == 1) {
        attrSrc = 'image=' + escape(source) + 
                  '&scroller=1' +
                  '&preStartBoxX=0' +
                  '&preStartBoxY=0' +
                  '&preEndBoxX=0' +
                   '&preEndBoxY=30' +
                  '&totalScrollFrames=' + $("#totalScrollFrames").val();
       } else {
        attrSrc = 'image=' + escape(source) + 
                  '&scroller=0';
      }
       $("#sourceImageSelect").attr("src",  
          '/design/sourceImageSelector.php?' + attrSrc);
    }

    $(".scroll_image").livequery("click", function() {
      var scroller = $(".scroll_image:checked").val();
      if (scroller == 0) {
        $("#scroller_controls").slideUp();
      } else {
        $("#scroller_controls").slideDown();
      }
      selectSourceImage(imageSource);
    });

    $(".animation_type").livequery("click", function() {
      $("#scrollLogoEOA").val($(this).val());
      loadPreview();
    });

    $(".help_popup").livequery("click", function() {
      $.fancybox({
          'href' : '/design/help.php?id=' + $(this).attr('id')
      });

      return false;
    });

    $("#userbar_preview").fadeOut('fast', function() {
      $("#userbar_preview").html('loading...').fadeIn()});
    if (($("#userbar_fetch_image_button").length == 1) && 
          ($("#userbar_fetch_image").val() != '') &&
          ($("#userbar_fetch_image").val() != 'http://www.yoursite.com/yourimage')) {
      $("#userbar_fetch_image_button").click();
    } else if (($("#userbar_upload_image_button").length == 1) && 
          ($("#userbar_upload_image_fullpath").val() != '')) {
      selectSourceImage($("#userbar_upload_image_fullpath").val());
    } else {
      loadPreview();
    }
//    $("input:text:visible:first").focus().select();

    $(".userbar_code").livequery("click", function() {
      $(this).focus();
      $(this).select();

      return false;
    });
    
    $(function() {
      $(".copy_to_clipboard").each(function() {
        //Create a new clipboard client
        var clip = new ZeroClipboard.Client();

        //Glue the clipboard client to the last td in each row
        var clipboardTrigger = $(this);
        clip.glue(clipboardTrigger[0]);

        //Grab the text from the parent row of the icon
        var content = clipboardTrigger.next().next().text();
        clip.setText(content);

        //Add a complete event to let the user know the text was copied
        clip.addEventListener('complete', function(client, text) {
          $.fancybox('<h1 style="text-align:center;">Copied!</h1>', {
            'autoDimension' : false,
            'width' : 230,
            'height' : 50,
            'padding' : 20
          });
        }); 
      });         
    });                  

  });
}

