getWindowSize = function(w) {
  w = w ? w : window;
  var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
  var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
  return [width, height]
}


var activeLink;
function resetArtistPopup(hoverLink) {
  activeLink = hoverLink;
  $('#artist_popup').html('<div class="ajax_spinner"><img src="images/ajax_indicator.gif"/>' + 
                          '<br/><br/>Loading...</div>');
  positionPopup('#artist_popup');
}


function positionPopup(div_id) {
  var offset = $(document).scrollTop();
  if(offset < 200) { offset = 200; }
  $(div_id).css({ left: '50px', top: 20 + offset + 'px' }).show();
}


function showPicPopup(hoverLink, path) {
  activeLink = hoverLink;
  $('#pic_popup').html('<img src="' + path + '"/>');
  positionPopup('#pic_popup');
}


var NavigateTo = {
  MonthYear: function(monthyear) {
    if(monthyear == "" || typeof monthyear == "undefined") { return; }
    
    var parts = monthyear.split(':');
    location.href = location.pathname + "?date[year]=" + parts[0] + "&date[month]=" + parts[1] + "&date[day]=1";
  }
};


$(document).ready(function() {
  $('input[type="text"],input[type="text"]').addClass('text');
  $('li:last-child').addClass('last');
  $('.dropdown-container').mouseover(function() { $('.dropdown', this).show(); });
  $('.dropdown-container').mouseout(function()  { $('.dropdown', this).hide(); });
});



Skedj = {

  selected_date: null,
  location_id: null,


  initPage: function() {
    this.setPageVariables();
    this.initHoverStates();
    this.initSchedulingDragDrop();
    this.initAssignmentEditing();
    this.initDateNavigation();
  },


  setPageVariables: function() {
    // Location
    var loc = $('div.Location');
    if(loc != null && loc.length > 0) {
      Skedj.location_id = loc[0].id.replace(/\D+/, '');
    }

    // Date
    var day = $('div.Day');
    if(day != null && day.length > 0) { 
      Skedj.selected_date = $.datepicker.parseDate('yy-mm-dd', day[0].id.replace(/[^0-9-]+/, ''))
    }
  },

  initHoverStates: function() {
    $('ul.Employees > li').hover(
        function() { $(this).addClass('hover'); },
        function() { $(this).removeClass('hover').removeClass('expanded'); }
    );
  },


  assignmentDateSelected: function(dateText, inst) {
    document.location.href = "/locations/" + Skedj.location_id + "/assignments/" + dateText;
  },

  initDateNavigation: function() {
    $('.DatePicker').datepicker({
      defaultDate:     Skedj.selected_date,
      dateFormat:      'yy/mm/dd',
      numberOfMonths:  3,
      showOtherMonths: true,
      onSelect:        Skedj.assignmentDateSelected
      /* showButtonPanel: true */
    });

    $('.DatePickerToggle').toggle(
      function() { $('.DatePicker').slideDown(); },
      function() { $('.DatePicker').slideUp(); }
    );

    $('.LocationToggle').toggle(
      function() { $('ul.Locations').slideDown(); },
      function() { $('ul.Locations').slideUp(); }
    );
  },

  initSchedulingDragDrop: function() {

    $('ul.Shifts ul.Positions ul.Assignments').sortable('destroy');
    $('ul.Shifts ul.Positions ul.Assignments').sortable({

      /**
       * connectWith is passed the same selector as the
       * one creating this sortable. This makes every sortable
       * in this group connected automatically to every other
       * sortable in the group.
       */
      connectWith: 'ul.Shifts ul.Positions ul.Assignments',

      /**
       * The update event is fired for each of three use cases,
       * with different parameters in each case.
       *
       *  a) CREATION: An initial drop of an employee onto a position
       *  b) REORDER:  Re-ordering the employees within a single position
       *  c) MOVE:     Moving an employee from one position to another
       */ 
      update: function(event, ui) {
      
        var item_id = ui.item[0].id.replace(/\D+/, '');
        var siblings = $(this).children();
        var sort_position = siblings.index(ui.item[0]);

        var position_id = containerId(this, '.Position');
        var location_id = containerId(this, '.Location');
        var shift_id = containerId(this, '.Shift');
        var day = containerId(this, '.Day');

        // MOVE
        if(ui.sender != null) {
          var assignment_id = item_id;

          $("#Shift" + shift_id).load(
            "/assignments/" + assignment_id, {
              'assignment[position_id]': position_id,
              'assignment[shift_id]':    shift_id,
              'assignment[sort_position]': sort_position,
              '_method': 'PUT'
            },
            function() { Skedj.initPage(); }
          );
        }

        // CREATION
        else if($(ui.item[0]).hasClass('Name')) {
          var user_id = item_id;

          $("#Shift" + shift_id).load(
            "/users/" + user_id + "/assignments", {
              'position_id': position_id,
              'location_id': location_id,
              'shift_id':    shift_id,
              'sort_position': sort_position,
              'date':        day
            },
            function() { Skedj.initPage(); }
          );
        }

        // REORDER
        else if($(ui.item[0]).hasClass('Assignment') && sort_position >= 0) {
          var assignment_id = item_id;

          $("#Shift" + shift_id).load(
            "/assignments/" + assignment_id, {
              'assignment[position_id]': position_id,
              'assignment[shift_id]':    shift_id,
              'assignment[sort_position]': sort_position,
              '_method': 'PUT'
            },
            function() { Skedj.initPage(); }
          );
        }
      }
    });

    $('ul.Employees > li').click(function() {
        $(this).addClass('expanded');
        var user_id = this.id.replace(/\D+/, '');
        var day = containerId(this, '.Day');
        $(this).children('.WeeklyStatus').load(
          "/users/" + user_id + "/weekly_status?date=" + day
        );
        
    });

    $('ul.Employees > li span.Name').draggable('destroy');
    $('ul.Employees > li span.Name').draggable({
      helper: 'clone',
      /*
      helper: function() {
        var copy = $(this).clone();
        copy.children('ul, div').remove();
        copy.removeClass('hover').removeClass('expanded');
        return copy.eq(0);
      },
      */
      revert: 'true',
      opacity: 0.5,
      connectToSortable: $('ul.Shifts ul.Positions ul.Assignments')
    });
  },

  initAssignmentEditing: function() {

    $('body').click(Skedj.Assignment.clearEditors);

    $('ul.Assignments span.DownArrow:not(.clickable)').addClass('clickable').toggle(

        function() {
          Skedj.Assignment.edit(containerId(this, '.Assignment'));
        },

        function() {
          Skedj.Assignment.clearEditors();
        }
    );
  }

};

Skedj.Assignment = {

  clearEditors: function() { $('.AssignmentEditOverlay').remove(); },

  edit: function(id) {
    Skedj.Assignment.clearEditors();
    var assignment_el = $('#Assignment' + id);

    $('body').append('<div id="AssignmentEditOverlay' + id +'" class="AssignmentEditOverlay EditOverlay"></div>');
    $('#AssignmentEditOverlay' + id).load('/assignments/' + id + '/edit', '', function() { Skedj.Assignment.positionEditor(id); });
    $('#AssignmentEditOverlay' + id).click(function(e) { e.stopPropagation(); });
  },

  positionEditor: function(id) {
    var assignment = $('#Assignment' + id);
    var editor = $('#AssignmentEditOverlay' + id);
    editor.css({
      position: 'absolute',
      top: assignment.position().top + assignment.height() - 1,
      left: assignment.position().left,
      width: assignment.width()
    });
    
  }

};



/**
 * containerId
 *
 * Finds the object/model id that pertains to a given element.
 * The selector string can match either the passed-in element, or
 * one of its parents.
 */
function containerId(el, parentQuery) {
  var query = $(el).parents(parentQuery);
  
  if(query.size() < 1) {
    query = $(el).filter(parentQuery);
  }

  if(query.size() < 1) {
    return null;
  } else {
    return query.attr('id').replace(/[^0-9:-]+/, '');
  }
}


$(document).ready(function() {

  Skedj.initPage();

});


$(document).ready(function() {
  if(typeof $('a.gallery').colorbox != 'undefined') {
    $('a.gallery').colorbox();
  }
});


$(document).ready(function() {
    var browser = navigator.platform;
    var flash = document.getElementById('impact_graphic');
    var image = document.getElementById('alt_impact');
    //alert(browser);
    if (browser == 'Win32' || browser.match(/Mac/i)) {
        flash.style.display = 'block';
        image.style.display = 'none';
    }
    else { //mobile device
        flash.style.display = 'none';
		var sPage = document.location.pathname;
		if (sPage == '/')
		{
			document.location.href='/main/mobile';
		}
		else
		{
			if (sPage != '/main/mobile')
			{
				image.style.display = 'block';
			}
		}
    }
});

/* ------------- ROLLOVERS ------------- */
// preload nav rollovers
if (document.images) {
	var mob_logo_tavern= new Image();
	var mob_logo_tavern_ro = new Image();
	var mob_logo_sdu= new Image();
	var mob_logo_sdu_ro = new Image();
	var mob_logo_cbl= new Image();
	var mob_logo_cbl_ro = new Image();
	
	var mob_txt_uptown= new Image();
	var mob_txt_uptown_ro = new Image();		
	var mob_txt_downtown= new Image();
	var mob_txt_downtown_ro = new Image();
	var mob_txt_lowry= new Image();
	var mob_txt_lowry_ro = new Image();	
	var mob_txt_wash= new Image();
	var mob_txt_wash_ro = new Image();	
	var mob_txt_tech= new Image();
	var mob_txt_tech_ro = new Image();	

	
    mob_logo_tavern.src = "http://www.tavernhg.com/images/mob_logo_tavern.png";
    mob_logo_tavern_ro.src = "http://www.tavernhg.com/images/mob_logo_tavern_ro.png";
    mob_logo_sdu.src = "http://www.tavernhg.com/images/mob_logo_sdu.png";
    mob_logo_sdu_ro.src = "http://www.tavernhg.com/images/mob_logo_sdu_ro.png";
    mob_logo_cbl.src = "http://www.tavernhg.com/images/mob_logo_cbl.png";
    mob_logo_cbl_ro.src = "http://www.tavernhg.com/images/mob_logo_cbl_ro.png";

    mob_txt_uptown.src = "http://www.tavernhg.com/images/mob_txt_uptown.png";
    mob_txt_uptown_ro.src = "http://www.tavernhg.com/images/mob_txt_uptown_ro.png";
    mob_txt_downtown.src = "http://www.tavernhg.com/images/mob_txt_downtown.png";
    mob_txt_downtown_ro.src = "http://www.tavernhg.com/images/mob_txt_downtown_ro.png";
    mob_txt_lowry.src = "http://www.tavernhg.com/images/mob_txt_lowry.png";
    mob_txt_lowry_ro.src = "http://www.tavernhg.com/images/mob_txt_lowry_ro.png";
    mob_txt_tech.src = "http://www.tavernhg.com/images/mob_txt_tech.png";
    mob_txt_tech_ro.src = "http://www.tavernhg.com/images/mob_txt_tech_ro.png";
    mob_txt_wash.src = "http://www.tavernhg.com/images/mob_txt_wash.png";
    mob_txt_wash_ro.src = "http://www.tavernhg.com/images/mob_txt_wash_ro.png";

   
}