/* =========================================================

// jquery.innerfade.js

// Datum: 2007-01-29
// Firma: Medienfreunde Hofmann & Baldes GbR
// Autor: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/

// ========================================================= */


(function($) {

$.fn.innerfade = function(options) {

  this.each(function(){   
    
    var settings = {
      animationtype: 'fade',
      speed: 'normal',
      timeout: 2000,
      type: 'sequence',
      containerheight: 'auto',
      runningclass: 'innerfade'
    };
    
    if(options)
      $.extend(settings, options);
    
    var elements = $(this).children();
  
    if (elements.length > 1) {
    
      $(this).css('position', 'relative');
  
      $(this).css('height', settings.containerheight);
      $(this).addClass(settings.runningclass);
      
      for ( var i = 0; i < elements.length; i++ ) {
        $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute');
        $(elements[i]).hide();
      };
    
      if ( settings.type == 'sequence' ) {
        setTimeout(function(){
          $.innerfade.next(elements, settings, 1, 0);
        }, settings.timeout);
        $(elements[0]).show();
      } else if ( settings.type == 'random' ) {
        setTimeout(function(){
          do { current = Math.floor ( Math.random ( ) * ( elements.length ) ); } while ( current == 0 )
          $.innerfade.next(elements, settings, current, 0);
        }, settings.timeout);
        $(elements[0]).show();
      }  else {
        alert('type must either be \'sequence\' or \'random\'');
      }
      
    }
    
  });
};


$.innerfade = function() {}
$.innerfade.next = function (elements, settings, current, last) {

  if ( settings.animationtype == 'slide' ) {
    $(elements[last]).slideUp(settings.speed, $(elements[current]).slideDown(settings.speed));
  } else if ( settings.animationtype == 'fade' ) {
    $(elements[last]).fadeOut(settings.speed);
    $(elements[current]).fadeIn(settings.speed);
  } else {
    alert('animationtype must either be \'slide\' or \'fade\'');
  };
  
  if ( settings.type == 'sequence' ) {
    if ( ( current + 1 ) < elements.length ) {
      current = current + 1;
      last = current - 1;
    } else {
      current = 0;
      last = elements.length - 1;
    };
  }  else if ( settings.type == 'random' ) {
    last = current;
    while (  current == last ) {
      current = Math.floor ( Math.random ( ) * ( elements.length ) );
    };
  }  else {
    alert('type must either be \'sequence\' or \'random\'');
  };
  setTimeout((function(){$.innerfade.next(elements, settings, current, last);}), settings.timeout);
};
})(jQuery);


var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
};

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
    var len = this.length;
    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0) {
      from += len;
    }
    for (; from < len; from++) {
      if (from in this && this[from] === elt) {
        return from;
      }
    }
    return -1;
  };
}

String.prototype.capitalize = function() {
  val = this.replace(/\_/," ");
  newVal = '';
  val = val.split(' ');
  for(var c=0; c < val.length; c++) {
    newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length);
  }
  return newVal;
};

String.prototype.urlEncode = function(){
  return escape(this).replace(/\//ig,'%2F')
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/* Simple lighbox */
;(function($){
  $.fn.simpleBox = function(content, settings) {
    settings = jQuery.extend({
      overlayBgColor:     '#000',
      overlayOpacity:      0.8
    }, settings || {});
    var jQueryMatchedObj = this;
    var content = content;

    function _initialize() {
      _start(this,jQueryMatchedObj);
      return false;
    }

    function _start(objClicked, jQueryMatchedObj) {
      _set_interface();
    }
  
    function _set_interface() {
    
      var html = '<div id="simplebox-overlay"></div>';
      html    += '<div id="simplebox"><div id="simplebox-inner"><div id="simplebox-content"></div><a href="#" class="close_me">Stäng</a></div></div>';
    
      $('body').append(html);
      $('#simplebox-content').append(content);
      var arrPageSizes = ___getPageSize();
      $('#simplebox-overlay').css({
        backgroundColor: settings.overlayBgColor,
        opacity : settings.overlayOpacity,
        width   : arrPageSizes[0],
        height  : arrPageSizes[1]
      }).fadeIn();
    
      var arrPageScroll = ___getPageScroll();

      $('#simplebox').css({
        top  : arrPageScroll[1] + (arrPageSizes[3] / 10),
        left : arrPageScroll[0]
      }).show();
      $('#simplebox-overlay, #simplebox .close_me').click(function() {
        _finish();
        return false;
      });
    
      $(document).keydown(function(objEvent) {
        escapeKey = 27;
        if ( objEvent == null ) {
          keycode = event.keyCode;
        } else {
          keycode = objEvent.keyCode;
        }

        if (keycode == escapeKey) {
          _finish();
        }
      });
      $(window).resize(function() {
        var arrPageSizes = ___getPageSize();
        $('#simplebox-overlay').css({
          width:    arrPageSizes[0],
          height:    arrPageSizes[1]
        });
        var arrPageScroll = ___getPageScroll();
        $('#simplebox').css({
          top:  arrPageScroll[1] + (arrPageSizes[3] / 10),
          left: arrPageScroll[0]
        });
      });
    }

    function _finish() {
      $('#simplebox').remove();
      $('#simplebox-overlay').fadeOut(function() {
        $('#simplebox-overlay').remove();
      });
    }
  
    function ___getPageSize() {
      var xScroll, yScroll;
      if (window.innerHeight && window.scrollMaxY) {  
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
      } else if (document.body.scrollHeight > document.body.offsetHeight) {
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
      } else {
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
      }
      var windowWidth, windowHeight;
      if (self.innerHeight) {
        if(document.documentElement.clientWidth){
          windowWidth = document.documentElement.clientWidth; 
        } else {
          windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientHeight) {
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
      } else if (document.body) {
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
      }
      if(yScroll < windowHeight){
        pageHeight = windowHeight;
      } else { 
        pageHeight = yScroll;
      }
      if(xScroll < windowWidth){  
        pageWidth = xScroll;    
      } else {
        pageWidth = windowWidth;
      }
      arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
      return arrayPageSize;
    }

    function ___getPageScroll() {
      var xScroll, yScroll;
      if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
      } else if (document.body) {
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;  
      }
      arrayPageScroll = new Array(xScroll,yScroll);
      return arrayPageScroll;
    }
    _initialize();
  };
})(jQuery);


var Teaser = Class.create();
Teaser.prototype = {
  initialize : function (element){
    this.element = $(element);
    if(this.element.hasClass('slideshow')) {
      this.slideShow();
    }
    var links = this.element.find('a');
    if (links.size() == 1) {
      element = this.element;
      element.click(function(event) {
        if (event.target.nodeName.toUpperCase() != 'OBJECT' && event.target.nodeName.toUpperCase() != 'EMBED') {
          window.location = links.get(0).href;
        }
        event.preventDefault();
        event.stopPropagation();
      })
      .addClass('has_proxy')
      .bind("mouseover mouseout", function(event) {
        element.toggleClass('hover');
        event.stopPropagation();
      });
    }
  },
  slideShow : function () {
    this.element.find('div.images').show().innerfade({ speed: 'slow', timeout: 3000, type: 'sequence'}); 
  }
};

var Pages = Class.create();
Pages.prototype = {  
  initialize : function() {
  },
  pagesShow : function () {
    $('div.teaser').each(function(key, teaser){
      var teaser = new Teaser(teaser);
    });
        
    if ($('#campaign_flash').size() == 1 && typeof swfobject != 'undefined') {
      var flashvars = {};
      if (typeof QueryString != 'undefined') {
        qs = new QueryString();
        if ((image_id = qs.get('image_id'))) {
          flashvars.imageID = image_id;
        }
      }
      flashvars.swfPath = "http://kampanj.Nordisk Hjälp.se/swf/main.swf";
      flashvars.xmlPath = "http://kampanj.Nordisk Hjälp.se/admin/genImgXml.php";
      
      swfobject.embedSWF("http://kampanj.Nordisk Hjälp.se/swf/loader.swf", "campaign_flash", "950", "430", "9", "#fff", flashvars, {'bgcolor':'#fff'});
    }


    $('.layout6 #c_1 > :first-child').before($("#page_meta").get());
    
    $('#registration_amount_wrap #amounts').find('input[@type=radio]').not('#registration_total_sum_other').click(function(){
      $('#registration_total_sum_user_defined').val('');
    }).end().end().end()
    .find('#registration_total_sum_other').click(function() {
      $("#registration_total_sum_user_defined").focus();
    })
    .end()
    .find('#registration_total_sum_user_defined').click(function(){
      $('#registration_total_sum_other').attr('checked', 'checked');
    });
    
    $('#registration_should_create_user').click(function(e) {
      if ($(this).attr('checked')) {
        $('#create_user').show();
      } else {
        $('#create_user').hide();
      }
    });
    
    $('form.donation p.secure').hide();
    
    $('ul.payment_methods input[@type=radio]').click(function() {
      this.blur();
      fieldset = $(this).parents('ul')[0];
      if (fieldset.id == 'bank_payments') {
        $('#creditcard_notice').hide();
        $('#direct_payment_notice').show();
      } else if (fieldset.id == 'creditcard_payments') {
        $('#direct_payment_notice').hide();
        $('#creditcard_notice').show();
      }
      $('ul.payment_methods li').removeClass('selected');
      $(this).parents('li').addClass('selected');
    });
    
    $('.sample-products input.add_product').click(function() {
      if ($('.sample-products input.add_product:checked').size() > 4) {
        $('.sample-products input.add_product').not(':checked').attr('disabled', true).parent().addClass('disabled');
      } else {
        $('.sample-products input.add_product').attr('disabled', false).parent().removeClass('disabled');
      }
    });
    
    $('#new_registration.tip #choose_delivery_method input[@type=radio]').click(function() {
      switch($(this).val()) {
        case 'email':
          $('#registration_message').val('').attr('disabled', false);
          break;
        case 'sms':
          $('#registration_message').val($('#sms_info').text()).attr('disabled', true);
          break;
      }
    });
    
    $('#website-survey').find('a.close').click(function(event) {
      $('#website-survey').slideUp();
      event.preventDefault();
      $.cookie('hide_website_survey', 'true', { expires: 30, path: '/' });
    }).end().find('a.open').click(function(event) {
      $.cookie('hide_website_survey', 'true', { expires: 30, path: '/' });
    });
    
  }  
};

var Shops = Class.create();
Shops.prototype = {  
 initialize : function() {

 },
 
 shopsPage: function() {
   $('.sample-products input.add_product').click(function(){
     if($('.sample-products input.add_product:checked').size() > 4){
       $('.sample-products input.add_product').not(':checked').attr('disabled', true).parent().addClass('disabled');
     }else{
       $('.sample-products input.add_product').attr('disabled', false).parent().removeClass('disabled');
     }
   });
 },
 
 shopsCategory : function () {
   $('.teasers div').each(function(key, teaser){
     teaser = new Teaser(teaser);
   });
 },
 shopsProduct : function () {
   $('.teasers div').each(function(key, teaser){
     teaser = new Teaser(teaser);
   });
 },
 
 shopsPage : function () {
   $('#user_organization').click(function() {
      if (this.checked) {
        $('#organization_fields').show();
      } else {
        $('#organization_fields').hide();
      }
    });
 }
};

var Orders = Class.create();
Orders.prototype = { 
 initialize: function() {
   
 },
 ordersNew: function() {
    
    $('#wod_info').hide().before('<a href="#">Mer information</a>').parent().find('a').toggle(function() {
      $('#wod_info').show();
    }, function(){
      $('#wod_info').hide();
    });
    
    if ((will_donate = document.getElementById('will_donate')) && will_donate.checked !== true) {
      $('#donation').hide();
      $(will_donate).click(function(){
        if ($(this).attr('checked')) { $('#donation').show().find('#donation_amount').focus(); }
        else { $('#donation').hide(); }
      });
    }
    
    if ((company_flag = document.getElementById('order_company_flag')) && company_flag.checked !== true) {
      $('#company_order').hide();
      $(company_flag).click(function(){
        if ($(this).attr('checked')) { 
          $('#company_order').show().find('#order_organization').focus(); 
          $('#invoice_details .credit_check').each(function(){ $(this).hide(); });
        } else { 
          $('#company_order').hide(); 
          $('#invoice_details .credit_check').each(function(){ $(this).show(); });
        }
      });
    }
    
    $('#recount').hide();
    $('table.checkout_cart input').each(function(){
      this.old_val = $(this).val();
    }).bind('change', function(){
      $('#recount').show();
    }).bind('keyup', function(){
      if ($(this).val() != this.old_val) {
        $('#recount').show();
        this.old_val = $(this).val();
      }
    });
    
    if ((order_payment_type_invoice = document.getElementById('order_payment_type_invoice')) && order_payment_type_invoice.checked !== true) {
      $('#invoice_details').hide();
    }
    $('input.toggle_payment_method').click(function(){
      if ($(this).val() == 'invoice') {
        $('#invoice_details').show().find('#order_civic_number').focus();
      } else {
        $('#invoice_details').hide();
      }
    });

    if ((seperate_invoice_address = document.getElementById('order_seperate_invoice_address')) && seperate_invoice_address.checked !== true) {
      $('#invoice_address').hide();
      $(seperate_invoice_address).click(function(){
        if ($(this).attr('checked')) {
          $('#invoice_address').show().find('#order_address').focus();
        }
        else {
          $('#invoice_address').hide();
        }
      });
    }
    
    $('a.show-pricelist').click(function(event) {
      $('#pricelist').toggle();
      $.scrollTo($('#pricelist'), 200);
      return false;
    });
    
    $('#submit_order').click(function() {
      $(this).attr("disabled", "disabled");
      $('#wait_indicator').show();
      $(this).parents('form').submit();
    });
    
    $('#user_details').each(function() {
      $(this).after('<a href="#">Använd andra adressuppgifter för den här beställningen</a>').next().click(function(event) {
        $('#user_details').toggle();
        $('#order_shipping_details').toggle();
        event.preventDefault();
      });
    });
 }
};



var Products = Class.create();
Products.prototype = {  
  initialize: function() {
    
  },
  productsShow: function() {
    var main_image = $('#c_3 div.images .primary-image img')[0];
    $('#c_3 div.images ul a').each(function(){
      var img = new Image();
      img.src = this.href;
      $(this).click(function(){
        $(main_image).attr('src', img.src);  
        return false;
      });
    });
  }
};

var ProductCategories = Class.create();
ProductCategories.prototype = {  
 initialize : function() {
 },
 productcategoriesShow : function () {
   $('.teasers div').each(function(key, teaser){
     teaser = new Teaser(teaser);
   });
 }
};

var FundRaisings = Class.create();
FundRaisings.prototype = {  
  initialize: function() {
    var searchDefault = $('input.search_query').attr("value");
    $('input.search_query').focus(function(){  
        if($(this).attr("value") == searchDefault) $(this).attr("value", "");  
    });  
    $('input.search_query').blur(function(){  
        if($(this).attr("value") == "") $(this).attr("value", searchDefault);  
    });
  },
  
  fundraisingsIndex: function() {
    
  },
  
  fundraisingsCreate: function() {
    this.fundraisingsNew();
  },
  
  fundraisingsShow: function() {
    var klass = this;
    klass.setTipView($('#help_fund_raising #choose_delivery_method input[@type=radio]:checked'));
    $('#help_fund_raising #choose_delivery_method input[@type=radio]').click(function() {
      klass.setTipView(this);
    });
    
  },
  
  setTipView: function(element) {
    switch($(element).val()) {
      case 'email':
        $('#sms_tip_form').hide();
        $('#email_tip_form').show();
        $('#sms_about').hide();
        $('#email_about').show();
        break;
      case 'sms':
        $('#email_tip_form').hide();
        $('#sms_tip_form').show();
        $('#sms_about').show();
        $('#email_about').hide();
        break;
    }
  },
  
  fundraisingsNew: function() {
    this.checkAvailable = function() {
      value = $('#fund_raising_short_name').val();
      if (value != '') {
        $('#wait_indicator').show();
        $.ajax({
          type: "GET",
          url: '/fund_raisings/available',
          data: "short_name="+value,
          success: function(result){
            $('#wait_indicator').hide();
            if (result == 'true') {
              $('#check_avalible').hide();
              $('#fund_raising_short_name').removeClass('taken');
              $('#fund_raising_short_name').addClass('available');
            } else {
              $('#check_avalible').show();
              $('#fund_raising_short_name').removeClass('available');
              $('#fund_raising_short_name').addClass('taken');
            }
          }
        });
      }
    };
    self = this;
    $('#fund_raising_short_name').change(function() {
      $(this).removeClass('taken');
      $(this).removeClass('available');
      self.checkAvailable();
    })
    $('button#check_avalible').click(function() {
      this.blur();
      self.checkAvailable();
      return false;
    });
    
    $("#fund_raising_in_school_class_contest").change(function(){
      if(this.value == "1"){
        $("#user_type_company").attr('checked',true);
        $('#user_organization').show();
      }
    });
    
    $("#user_type_person, #user_type_company").change(function(){
      self.setDisplayForUserTypeCompany(this);
    });
    self.setDisplayForUserTypeCompany($("#user_type_person"));
  },
  
  setDisplayForUserTypeCompany: function(el){
    if(el.value == '1'){
      $('#user_organization').show();
    }else{
      $('#user_organization').hide();
    }
  }
};

var Users = Class.create();
Users.prototype = { 
  initialize: function() {
  },
  usersNew: function() {
    $('#user_organization').click(function() {
      if (this.checked) {
        $('#organization_fields').show();
      } else {
        $('#organization_fields').hide();
      }
    });
  }
}

if(typeof(Prototype) != 'undefined') {
  Event.onReady(setup_players);
}else if(typeof(jQuery) != 'undefined'){
  $(document).ready(setup_players);
}else if(typeof(DOMAssistant) != 'undefined'){
  DOMAssistant.DOMReady(setup_players); 
}

function setup_players(){
  players = getElementsByClassName(document, "div", "mediaplayer");
  for(var i=0; i<players.length; i++){
    create_player(players[i]);
	}
}

function create_player(el) {
  var options = {
    'width' : 320,
    'height' : 260
  };  
  
  el.getElementsByTagName("a")[0].style.display = 'none';    
  option_tags = el.getElementsByTagName("span");
  for(var i=0; i<option_tags.length; i++){
    options[option_tags[i].className] = option_tags[i].innerHTML;
  }
  options['id'] = el.id;
  swfobject.embedSWF("/swf/mediaplayer.swf", el.id, options['width'], options['height'], '7', "", options, {"allowfullscreen":"true"});
}

/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Date: 2/19/2008
 * @author Ariel Flesler
 * @version 1.3.3
 */
;(function( $ ){

 var $scrollTo = $.scrollTo = function( target, duration, settings ){
   $scrollTo.window().scrollTo( target, duration, settings );
 };

 $scrollTo.defaults = {
   axis:'y',
   duration:1
 };

 //returns the element that needs to be animated to scroll the window
 $scrollTo.window = function(){
   return $( $.browser.safari ? 'body' : 'html' );
 };

 $.fn.scrollTo = function( target, duration, settings ){
   if( typeof duration == 'object' ){
     settings = duration;
     duration = 0;
   }
   settings = $.extend( {}, $scrollTo.defaults, settings );
   duration = duration || settings.speed || settings.duration;//speed is still recognized for backwards compatibility
   settings.queue = settings.queue && settings.axis.length > 1;//make sure the settings are given right
   if( settings.queue )
     duration /= 2;//let's keep the overall speed, the same.
   settings.offset = both( settings.offset );
   settings.over = both( settings.over );

   return this.each(function(){
     var elem = this;
     var $elem = $(elem);
     var t = target;
     var toff;
     var attr = {};
     var win = $elem.is('html,body');
     switch( typeof t ){
       case 'number'://will pass the regex
       case 'string':
         if( /^([+-]=)?\d+(px)?$/.test(t) ){
           t = both( t );
           break;//we are done
         }
         t = $(t,this);// relative selector, no break!
       case 'object':
         if( t.is || t.style )//DOM/jQuery
           toff = (t = $(t)).offset();//get the real position of the target 
     }
     $.each( settings.axis.split(''), function( i, axis ){
       var Pos  = axis == 'x' ? 'Left' : 'Top',
         pos = Pos.toLowerCase(),
         key = 'scroll' + Pos,
         act = elem[key],
         Dim = axis == 'x' ? 'Width' : 'Height',
         dim = Dim.toLowerCase();

       if( toff ) {//jQuery/DOM
         attr[key] = toff[pos] + ( win ? 0 : act - $elem.offset()[pos] );

         if( settings.margin ){//if it's a dom element, reduce the margin
           attr[key] -= parseInt(t.css('margin'+Pos)) || 0;
           attr[key] -= parseInt(t.css('border'+Pos+'Width')) || 0;
         }

         attr[key] += settings.offset[pos] || 0;//add/deduct the offset

         if( settings.over[pos] ) {//scroll to a fraction of its width/height
           attr[key] += t[dim]() * settings.over[pos];
         }
       } else {
         attr[key] = t[pos];//remove the unnecesary 'px'
       }

       if( /^\d+$/.test(attr[key]) )//number or 'number'
         attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );//check the limits

       if( !i && settings.queue ){//queueing each axis is required          
         if( act != attr[key] )//don't waste time animating, if there's no need.
           animate( settings.onAfterFirst );//intermediate animation
         delete attr[key];//don't animate this axis again in the next iteration.
       }
     });      
     animate( settings.onAfter );      

     function animate( callback ){
       $elem.animate( attr, duration, settings.easing, callback && function(){
         callback.call(this, target);
       });
     };
     function max( Dim ){
       var el = win ? $.browser.opera ? document.body : document.documentElement : elem;
       return el['scroll'+Dim] - el['client'+Dim];
     };
   });
 };

 function both( val ){
   return typeof val == 'object' ? val : { top:val, left:val };
 };

})( jQuery );

function Controller() {
  s = document.getElementsByTagName('body')[0].id.split('-');
  this.page = s[0].capitalize();
  if (s[1]) {
    this.action = s[0].replace(/_/g,'') + s[1].substring(0,1).toUpperCase() + s[1].substring(1).replace(/_/g,'');
  } else {
    this.action = false;
  }
  this.controllers = ['Pages', 'Shops', 'Orders', 'Products', 'PrintSettings', 'ProductCategories', 'FundRaisings', 'Users'];
  this.dispatch = function() {
    if (this.controllers.indexOf(this.page) != -1) {
      try {
        eval('var '+this.page.toLowerCase()+' = new '+this.page+'();');
        eval(this.page.toLowerCase()+'.'+this.action+'();');
      } catch (err) {
        return;
      }
    }
  };
}

function QueryString(qs) { // optionally pass a querystring to parse
  this.params = new Object();
  this.get = function (key, default_) {
    // This silly looking line changes UNDEFINED to NULL
    if (default_ == null) { default_ = null };
    var value = this.params[key];
    if (value==null) { value = default_ };
    return value;
  };
  
  if (qs == null) {
    qs=location.search.substring(1,location.search.length);
  }

  if (qs.length == 0) { return; }

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
  qs = qs.replace(/\+/g, ' ');
  var args = qs.split('&'); // parse out name/value pairs separated via &
  
// split out each name=value pair
  for (var i=0;i<args.length;i++) {
    var value;
    var pair = args[i].split('=');
    var name = unescape(pair[0]);

    if (pair.length == 2) {
      value = unescape(pair[1]);
    } else {
      value = name;
    }
    this.params[name] = value;
  }
}


function setStyleSheetByTitle(title) {
   var i, a;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1
        && a.getAttribute("title")) {
       a.disabled = true;
       if (a.getAttribute("title") == title) {
         a.disabled = false;
        }
     }
   }
}


jQuery.cookie = function(name, value, options) {
  if (typeof value != 'undefined') { // name and value given, set cookie
      options = options || {};
      if (value === null) {
          value = '';
          options.expires = -1;
      }
      var expires = '';
      if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
          var date;
          if (typeof options.expires == 'number') {
              date = new Date();
              date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
          } else {
              date = options.expires;
          }
          expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
      }
      // CAUTION: Needed to parenthesize options.path and options.domain
      // in the following expressions, otherwise they evaluate to undefined
      // in the packed version for some reason...
      var path = options.path ? '; path=' + (options.path) : '';
      var domain = options.domain ? '; domain=' + (options.domain) : '';
      var secure = options.secure ? '; secure' : '';
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else { // only name given, get cookie
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
};

$(document).ready(function() {
  
  var GpReason = {};
  var reasons = $('div.gp_reasons div.reason:not(.my_reason)');
      
  GpReason.show = function(element, options) {
    var original = $(element);

    // window.location.hash = 'active_' + original.attr('id');

    var copy = original.clone();

    copy.attr('id', 'active_reason')
      .css('visibility', 'hidden')
      .insertBefore('#wrap');
    
    var document_width = $(document).width();
    var wrap_width     = $('#wrap').width();
    var wrap_margin    = (document_width - wrap_width) / 2;
    var image_size     = copy.find('img:first').outerHeight();

    var offset = original.offset();
   
    var options = jQuery.extend({
      original_top: offset.top,
      original_left: offset.left
    }, options || {});

    options = jQuery.extend({
      top:  (options.original_top - copy.height() + (image_size - parseInt(copy.css('padding-top')))),
      left: (options.original_left - parseInt(copy.css('padding-left'))),
      force_reversed: false
    }, options || {});

    if ((options.left + copy.width()) > (document_width - wrap_margin)) {
      copy.addClass('reversed');
      options.left = options.left - (copy.width() - image_size);
    }
    
    if (options.force_reversed && !copy.hasClass('reversed')) {
      copy.addClass('reversed');
    }
    
    var current_index = reasons.index(element);
        
    function previous(e) {
      e.preventDefault();
      GpReason.hide();
      var previous_index = ((current_index != 0) ? current_index - 1 : (reasons.size() - 1));
      GpReason.show(reasons.get(previous_index), {
        original_top: options.original_top,
        left: options.left,
        force_reversed: copy.hasClass('reversed')
      })
    }

    function next(e) {
      
      e.preventDefault();
      GpReason.hide();
      var next_index = ((current_index != reasons.size() - 1) ? current_index + 1 : 0);
      GpReason.show(reasons.get(next_index), {
        original_top: options.original_top,
        left: options.left,
        force_reversed: copy.hasClass('reversed')
      });
    }
    
    copy.append('<a href="#" id="previous_reason" class="previous">«</a>')
    .find('#previous_reason').click(previous).end()
    .append('<a href="#" id="next_reason" class="next">»</a>')
    .find('#next_reason').click(next);
    
    copy.css('top', options.top + 'px')
      .css('left', options.left + 'px')
      .append('<a href="#" class="close">Stäng</a>')
      .find('a.close').click(function(e) {
        e.preventDefault();
        GpReason.hide();
      }).end().css('visibility', 'visible');
      
    $(document).bind('keyup.gp_reasons', function(e) {
      switch(e.keyCode) {
        case 27:
          GpReason.hide();
          break;
        case 37:
          previous(e);
          break;
        case 39:
          next(e);
          break;
      }
    });
    
  };

  GpReason.hide = function() {
    $('#active_reason').remove();
    $(document).unbind('keyup.gp_reasons');
    // window.location.hash = '';
  };
  
  // if (window.location.hash != '') {
  //   var element = $(window.location.hash.replace('active_','')).get(0);
  //   if (typeof element != 'undefined') {
  //     GpReason.show(element);
  //   }
  // }
  
  GpReason.setRandomReason = function() {
    var reasons = [
      'Nordisk Hjälps arbete tilltalar mig utifrån att man hjälper alla barn i nöd. Jag har svårt för de organisationer där man har fadderbarn. Vad händer i en by där ett barn är ”adopterat” och får hjälp och andra inte får det?',
      'Jag vill vara med och kämpa för att alla barn ska ha möjlighet att gå i skolan, få tillgång till rent vatten och kunna äta sig mätta. Och att de skall få rätt till läkarvård och vaccinationer. Att bli Världsförälder var ett mycket lätt beslut att ta, ingen kan göra allt men alla kan göra något!',
      'Att kunna hjälpa barn här hemma och ute i världen känns både viktigt och självklart Barnens situation berör mig djupt och jag vill vara med och kämpa för att ge dem alla en bättre start i livet. Att det blev just Nordisk Hjälp är att jag litar fullkomligt på er förmåga att använda hjälpen där den behövs.',
      'Vi har valt att bli Världsföräldrar framför allt för att som Världsförälder hjälper man de barn som mest behöver hjälpen, inte ett utvalt barn. Det känns också bra att stödja Nordisk Hjälp då de arbetar enligt barnkonventionens ”punkter”. Att Nordisk Hjälp också kan påverka makthavare att prioritera barns rättigheter är väldigt viktigt för mig',
      'Genom att stödja Nordisk Hjälps arbete är jag med på ett ”litet hörn” som når ”maktens män” i FN:s medlemsländer. Att Nordisk Hjälp har tillträde till maktens korridorer och kan påverka länders politiska agerande i frågor som rör barn är viktigt – för barnen är ju världens framtid.',
      'Jag tror att många liksom jag själv känner stor frustration och hjälplöshet när man ser allt lidande runt om i världen. Man vill göra något men man vet kanske inte riktigt hur. Genom att bli världsförälder skapas möjlighet till delaktighet, att kunna vara med och hjälpa de mest utsatta barnen runt om i världen. För mig finns det inget argument för att inte bli Världsförälder.',
      'Även om jag i Sverige lever ett tryggt liv är det omöjligt för mig att blunda för orättvisor och misär i andra delar av världen. Alla kan göra skillnad! Du också!',
      'Kanske man ska ställa frågan varför blev jag inte världsförälder tidigare? Jag tror stenhårt på det konceptet. Det är förvånade hur stor nytta en 100-lapp kan göra. Skillnad mellan liv och död!',
      'Det är för mig naturligt att vilja hjälpa. 100 kronor i månaden kan tyckas lite men om vi alla hjälps åt kan vi tillsammans skapa bättre förutsättningar för barn runt om i världen.',
      'Att hjälpa till är för mig en självklarhet och jag tycker om det strategiska och långsiktiga sätt som Nordisk Hjälp arbetar på. Att man angriper underliggande orsaker och inte bara symtom.',
      'Jag blev Världsförälder för at jag ville göra något för de mest utsatta i världen, barnen. Det är allas vårt ansvar. Nordisk Hjälp känns som en bra organisation som har tydliga värderingar och tydligt mandat att kunna hjälpa till. Nordisk Hjälp är också en internationell accepterad organisation som får tillträde där det behövs.',
      'Jag blev Världsförälder för att jag ville hjälpa. Att sedan kunna bli en ”förälder” till alla världens barn känns för mig bättre än att skaffa ett specifikt fadderbarn.',
      'Jag blev världsförälder då det finns miljontals barn runtom i världen som inte har samma trygga omvärld som mina barn har. Alla har vi ett ansvar att hjälpa de som har det svårt.',
      'Jag blev Världsförälder då jag insåg att min lilla hjälp kan göra förändring. Att stå och se på är inget alternativ för mig.',
      'Jag blev Världsförälder då jag anser att Nordisk Hjälp är en pålitlig organisation med stor bredd, både geografiskt och insatsmässigt. Och då jag vill vara med och förändra livet till något bättre för barn som har det svårt.',
      'Det går att skydda barn mot våld, övergrepp och exploatering. Det går att ge dem trygghet, utbildning och mat för dagen. Och det går att befria barn från ett liv som soldat, gatubarn eller prostituerad. Därför blev jag världsförälder!',
      'Alla har vi ett val. Antingen gör du ingenting – eller så gör du någonting. Tillsammans kan vi förändra förutsättningarna för miljontals barn världen över.',
      'Nordisk Hjälp, världens ledande barnrättsorganisation, finns på plats i regeringskorridorer, slumområden, flyktingläger och avlägsna byar och arbetar dygnet runt för att hjälpa världens mest utsatta barn – oavsett nationalitet, religion eller landets politiska ledning.',
      'Genom att bli världsförälder är du med i kampen för att alla barn i hela världen ska få den barndom som de har rätt till. Vi kanske inte kan förändra världen idag, men allt stort börjar med något litet.'
    ];
    $('#gp_reason_body').text(reasons[Math.floor(Math.random()*reasons.length)]);
  };
  
  $('#new_gp_reason textarea').after('<p class="sample_reason">Behöver du lite inspiration? <a href="#" id="set_random_reason">Ge mig ett förslag på skäl</a></p>')
  .parent().find('#set_random_reason').click(function(e) {
    GpReason.setRandomReason();
    e.preventDefault();
  })
  
  reasons.click(function(e) {
    e.preventDefault();
    GpReason.hide();
    GpReason.show(this);
  });
  
  
  $('#shop_header').find('#full_cart').hide().end()
  .find('#toggle_cart').click(function(event) {
    $(this).toggleClass('open');
    $('#full_cart').toggle();
    event.preventDefault();
  });
  
  $('#update_cart').click(function(event) {
    $('#toggle_cart').addClass('open');
    $('#full_cart').show();
  });
  
  $('#order_seperate_shipping_address').click(function(event) {
    $('#seperate_shipping_address').toggle();
  });

  $('#order_create_user').click(function(event) {
    $('#create_user').toggle();
  });
  
  if (window.print) {
    $('#page_actions  a.print').click(function(event){
      event.preventDefault();
      window.print();
    });
  }
  
  $('#user-greeting').hide();
   if($("input[@id='print_setting_predef_greeting_false']:checked").val() == 'false'){
     $('#user-greeting').show();
     $('#toggle_greeting_in_english').hide();
   }
   
   $('#user-greeting ul.font_faces input').click(function() {
     if($(this).val() == 'false'){
       $('#user_defined_font_face').show();
     } else {
       $('#user_defined_font_face').hide();
     }
   });
   $('.predef-greeting:checked').parent().addClass('active');
   $('.predef-greeting').click(function() {
     $('.predef-greeting').parent().removeClass('active');
     if($(this).val() == 'false'){
       $('#user-greeting').show();
       $('#toggle_greeting_in_english').hide();
     } else {
       $(this).parent().addClass('active')
       $('#user-greeting').hide();
       $('#toggle_greeting_in_english').show();
     }
   });
  
  //
  // Disable submits on click
  //
  //  $('input[@type=submit], input[@type=image]').click(function(){
  //    this.disabled = true;
  //    this.blur();
  //    $(this).parents('form')[0].submit();
  //    return false;
  //  });

  $('.donation #c_1 .sign_online a').attr('target', '_blank');

  $('input.clear_content').each(function(){
    this.old_value = this.value;
  }).focus(function(){
    if (this.value == this.old_value) { this.value = ''; }
  }).blur(function(){
    if (this.value == '') { this.value = this.old_value; }
  });

  $('#page_actions div.share').hover(
    function(event) {
      $('#page_actions .share_links').show();
    },
    function(event) {
      $('#page_actions .share_links').hide();
    }
  ).find('a.share').click(function(event) {
    event.preventDefault();
  });
  $('ul.share_links a.pop, .share a.pop').click(function(event) {
    window.open(this.href, $(this).text(),"left=2,top=0,width=600,height=450,resizable=no,scrollbars=no,status=no,screenX=0,screenY=0");
    event.preventDefault();
  });
  
  $(".select_on_click").click(function(){ this.select(); } );
  
  $('#reset_funding_target').click(function(event) {
    $('#will_fund').slideUp("slow");
    $.get('/fundings/reset_funding_target.js');
    event.preventDefault();
  });
  

  $('table.cart span.wod_info').hide().before('<a href="#">Mer information</a>').parent().find('a').toggle(function() {
    $(this).parent().find('span.wod_info').show();
  }, function() {
    $(this).parent().find('span.wod_info').hide();
  });
  
  if ((will_donate = document.getElementById('will_donate'))) {
    if (will_donate.checked !== true) {
      $('#donation').hide();
    }
    $(will_donate).click(function(){
      if ($(this).attr('checked')) { $('#donation').show().find('#donation_amount').focus(); }
      else { $('#donation').hide(); }
    });
  }
  
  if ((will_donate_not_editable = document.getElementById('will_donate_not_editable'))) {
    if (will_donate_not_editable.checked !== true) {
      $('#donation_not_editable').hide();
    }
    $(will_donate_not_editable).click(function(){
      if ($(this).attr('checked')) { $('#donation_not_editable').show().find('#donation_amount_not_editable').focus(); }
      else { $('#donation_not_editable').hide(); }
    });
  }
  
  $('#shop_print_settings input.black_and_white_choice').filter(':checked').each(function() {
    if ($(this).val() == 'true') {
      $('#shop_print_settings div.colour_choice').hide();
    }
  }).end().click(function() {
    if ($(this).val() == 'true') {
      $('#shop_print_settings div.colour_choice').hide();
    } else {
      $('#shop_print_settings div.colour_choice').show();
    }
  });
  
  $('#recount').hide();
  $('table.checkout_cart input').each(function(){
    this.old_val = $(this).val();
  }).bind('change', function(){
    $('#recount').show();
  }).bind('keyup', function(){
    if ($(this).val() != this.old_val) {
      $('#recount').show();
      this.old_val = $(this).val();
    }
  });
  
  if (( product_page = $('#shop_product.show'))) {
    var main_image = product_page.find('#c_1 div.images div.primary img')[0];
    product_page.find('#c_1 div.images ul a').each(function(){
      var img = new Image();
      img.src = this.href;
      $(this).click(function(event){
        $(main_image).attr('src', img.src);  
        event.preventDefault();
      });
    });
  }

  $('div.add_to_cart form').submit(function(event) {
    var form = $(this);
    var article_number = form.find('input[name="article_number"]').val();
    var name           = form.find('input[name="name"]').val();
    var quantity       = parseInt(form.find('input[name="quantity"]').val());
    var product_page   = $('#shop_category').size() != 1;
    var in_list = form.parents('div.products').size() == 1;
    if (!product_page) {
      var page_name = 'Product list on category page';
    } else if (!in_list) {
      var page_name = 'Product page'
    } else {
      var page_name = 'Product list on product page'
    }
    if (typeof pageTracker != 'undefined') {
      pageTracker._trackEvent('Add to cart', page_name, name + ' ' + article_number, quantity);
    }
  });
  
  if ((order_payment_type_invoice = document.getElementById('order_payment_type_invoice')) && order_payment_type_invoice.checked !== true) {
    $('#invoice_details').hide();
  }
  $('input.toggle_payment_method').click(function(){
    if ($(this).val() == 'invoice') {
      $('#invoice_details').show().find('#order_birth_date').focus();
    } else {
      $('#invoice_details').hide();
    }
  });

  if ((seperate_invoice_address = document.getElementById('order_seperate_invoice_address')) && seperate_invoice_address.checked !== true) {
    $('#invoice_address').hide();
    $(seperate_invoice_address).click(function(){
      if ($(this).attr('checked')) {
        $('#invoice_address').show().find('#order_address').focus();
      }
      else {
        $('#invoice_address').hide();
      }
    });
  }
  
  $('#submit_order').click(function() {
    $(this).attr("disabled", "disabled").val("Skickar beställning ...");
    $('#wait_indicator').show();
    $(this).parents('form').submit();
  });
  
  
  var controller = new Controller();
  if (controller.action) {
    controller.dispatch();
  }
  
  $('.sample-products input.add_product').click(function(){
     if($('.sample-products input.add_product:checked').size() > 4){
       $('.sample-products input.add_product').not(':checked').attr('disabled', true).parent().addClass('disabled');
     }else{
       $('.sample-products input.add_product').attr('disabled', false).parent().removeClass('disabled');
     }
   });
   $('textarea.force_maxlength').keydown(function(event) {
     if (!(this.attributes && (maxlength = this.attributes.maxlength))) { return; }
     if (jQuery.inArray(event.keyCode, [8, 46, 37, 38, 39, 40]) != -1) { return; }
     if (parseInt($(this).val().length) >= parseInt(this.attributes.maxlength.nodeValue)) {
       return false;
     }
   });
   $('input.force_maxlength').keydown(function(event) {
      if (!(this.attributes && (maxlength = this.attributes.maxlength))) { return; }
      if (jQuery.inArray(event.keyCode, [8, 46, 37, 38, 39, 40]) != -1) { return; }
      if (parseInt($(this).val().length) >= parseInt(this.attributes.maxlength.nodeValue)) {
        return false;
      }
    });
});

