(function($) {
  $(function() {
    /**
      * Login, registration and lost password form logic
      */
    var $login            = $('#sidebar #login-form');
    var $lostPassword     = $('#sidebar #lost-password-form');

    if ($login && $lostPassword) {
      // If we're on the 'lost password' page, show the 'lost password' form.
      if (location.href.match(/action=lostpassword/gi)) {
        $login.hide();    
      } else if (location.href.match(/(wp\-login\.php)|(logg\-inn)/gi)) {
        $lostPassword.hide();
      }

      $('#sidebar a.lost-password').click(function() {
        $login.hide();
        $lostPassword.show();
        return false;
      });

      $('#sidebar a.login').click(function() {
        $lostPassword.hide();
        $login.show();
        return false;
      });
    } // if ($login && !$lostPassword)

    /**
      * Slides in a modal dialog.
      */  
    var slideDialogIn = function(dialog) {
      dialog.overlay.fadeIn('fast', function () {
    		dialog.container.slideDown('normal', function () {
    			dialog.data.fadeIn('fast');
    		});
    	});
    };


    /**
      * Slides out a modal dialog.
      */  
    var slideDialogOut = function(dialog) {
    	dialog.data.fadeOut('fast', function () {
    		dialog.container.slideUp('normal', function () {
    			dialog.overlay.fadeOut('fast', function () {
    				$.modal.close();
    			});
    		});
    	});
    };


    /**
      * Initializes the Google Map
      */
    var $map = $('#map');

    if ($map.length > 0) {
      var latitude  = 59.913287;
      var longitude = 10.743682;
      var $vcard    = $('.contact .vcard').clone();
      var map       = new GMap2($map[0]);
      var marker    = new GMarker(new GLatLng(latitude, longitude), {
        title: 'Galligani AS',
        clickable: true,
      });

      map.disableDragging();
      map.setCenter(new GLatLng(latitude + 0.0006, longitude), 16);
      map.addOverlay(marker);
  
      if ($vcard.length > 0) {
        GEvent.addListener(marker, 'click', function() {
          marker.openInfoWindow($vcard[0]);
        });
      }
    } // Google Map


    /*
     * Product Set Picture logic
     */
    $('.product-set div.picture a').click(function() {
      var $$            = $(this);
      var src           = $$.attr('href');
      var classes       = $$.attr('class');
      var width         = classes.match(/w([^\s]+)/i)[1];
      var height        = classes.match(/h([^\s]+)/i)[1];
      var dialogHeight  = parseInt(height, 10) + 5;

      $.modal('<img src="' + src + '" width="' + width + '" height="' + height + '"/>', {
        onOpen        : slideDialogIn,
        onClose       : slideDialogOut,
        containerCss  : {
          height      : dialogHeight + 'px',
          width       : width + 'px',
        },
      });

      return false;
    });


    /**
      * Add product to wish list logic
      */
    $('.product-set table.products td.list button.add').click(function() {
      if (!Galligani || !Galligani.themeUri) {
        return true;
      }

      var $$              = $(this);
      var $row            = $$.parents('tr');
      var uri             = Galligani.themeUri + '/ajax/wish-list.php';
      var productSetTitle = $$.parents('table').find('caption .product-set-title').text();
      var productTitle    = $row.find('td.title').text();
      var productId       = $row.find('td.list input[name="product_id"]').val();
      var action          = $$.attr('class');
      var requestData     = {
        action            : action,
        current_user_id   : Galligani.currentUserId,
        product_set_title : productSetTitle,
        product_set_uri   : location.href,
        product_title     : productTitle,
        product_id        : productId,
      };

      $.get(uri, requestData, function(data) {
        var $dialog = $(data);

        $dialog.modal({
          onOpen        : slideDialogIn,
          onClose       : slideDialogOut,
          containerCss  : {
            'height'            : '200px',
            'width'             : '400px',
            'text-align'        : 'left',
            'background-image'  : 'none',
          }
        });
      });

      return false;
    });


    /**
      * Wish List table editing logic
      */
    $('#content.wish-list table tr.new td.title input').change(function() {
      var $$ = $(this);
      if ($$.val() != '') {
        var $tbody     = $$.parents('tbody');
        var lastTitle  = $tbody.find('tr:last td.title input').val();
    
        // Only append a new row if the last title is empty
        if (lastTitle != '') {
          var $row      = $$.parents('tr').clone(true).find('td.title input').val('').end();
          $tbody.append($row);
        }
      }
    });
    

    /**
      * Wish List URI selection logic
      */
    $('#wish-list-meta input.text').click(function() {
      this.select();
    });


    /**
      * jQuery UI Datepicker hookup
      */
    $.datepicker.setDefaults($.datepicker.regional['no']); 
    $('input.date').datepicker({
      altField        : 'input.date',
      altFormat       : 'dd.mm.yy',
      dateFormat      : 'dd.mm.yy',
      defaultDate     : 0,
      firstDay        : 1,
      constrainInput  : true,
      duration        : 'fast',
    }).attr('readonly', 'readonly');
    

    /**
      * jQuery UI Spinner hookup
      */
    $('#content.wish-list table td.quantity input').spinner({
      min: 0,
      max: 1000,
    });


    /**
      * Wish List title default text
      */
    var firstName = $('input#first-name').val();
    var uneditedTitle = firstName + ' og «Bedre halvdel» sin ønskeliste';
    $('input#wish-list-title').val(uneditedTitle).addClass('unedited').focus(function() {
      $$ = $(this);
      
      if ($$.val() == uneditedTitle) {
        $$.val('').removeClass('unedited');
      }
    }).blur(function() {
      $$ = $(this);
      
      if ($$.val() == '') {
        $$.val(uneditedTitle).addClass('unedited');
      }
    }).parents('form').submit(function() {
      $(this).find('input.unedited').val('');
    });
  });
})(jQuery);
