//---------------------------------------
//-- To Do
//--  - Transparent PNG BG's for schedule
//--  - Allow two of the same id (Lab), show its a lab somewhere
//---------------------------------------

window.addEvent('domready', function()
{

  var count = 0;   //-- Keep track of the course number
  var countS = 0;  //-- Keep track of the section number
  var countUp = 0; //-- Keep track of the amount of courses

  //var colors = new Array('#FFE3E3', '#F1F5EC', '#E0ECFF');
  //var colorH = new Array('#CC0000', '#006633', '#206CFF');

  var colors = new Array('#FFC0FF', '#FFFFC0', '#FFC0C0', '#C0FFC0', '#C0FFFF', '#FFDCAF', '#CFD0FF', '#D1E7EF', '#E0BEFF', '#EEEEEE');
  var colorH = new Array('#EF95EF', '#FFF36F', '#FF8F8F', '#78EF77', '#77EFEF', '#FFB24F', '#9FA0FF', '#8BC9DF', '#C483FF', '#CCCCCC');

  var dragging;

  var tC = 0;

  //----------------
  //-- Window events
  //----------------

    window.addEvent('resize', function(e)
      {
        $('courseOptions').setStyle('display', 'none');
      });

    window.addEvent('mousedown', function(e)
      {
        e = new Event(e);

        x = $('courseOptions').getPosition().x;
        y = $('courseOptions').getPosition().y;
        w = $('courseOptions').getCoordinates().width;
        h = $('courseOptions').getCoordinates().height;

        if( ! ( e.page.x > x && e.page.y > y && e.page.x < (x + w) && e.page.y < (y + h) ) )
          {
            $('courseOptions').setStyle('display', 'none');
          }

      });

  //-------------------------------
  //-- Add functionality to options
  //-------------------------------

    $$('#courseOptions div').each( function(div)
      {
        div.addEvent('click', function(e)
          {
            $$('#courseOptions div').each( function(div) { div.getFirst().setStyle('display', 'none'); } );

            if( div.getFirst().getStyle('display') == "block" )
              {
                div.getFirst().setStyle('display', 'none');
              }
             else
              {
                div.getFirst().setStyle('display', 'block');
                cid = $('courseOptions').courseId;

                nColorId = div.id.substr(7).toInt() - 1;
                nColorH = colorH[nColorId];
                nColor = colors[nColorId];

                //-- Update slider

                  $$('.slider' + cid
                     + ', .courseTitle' + cid
                     + ', .cW' + cid
                     + ', .courseArrow' + cid
                     + ', .sCRC' + cid).each(function(div)
                    {
                      div.setStyle('background-color', nColorH);
                      div.colorId = nColorId;
                    });

                //-- Update slider

                  $$('.courseSectionD' + cid
                     + ', .cS' + cid).each(function(div)
                    {
                      div.setStyle('background-color', nColor);
                      if(div.hasClass('sCourseOn')) div.setStyle('border-color', nColorH);
                      div.colorId = nColorId;
                    });
              }
          });
      });

  //------------------
  //-- AddCourseButton
  //------------------

  //$('addCourseButton').addEvent('click', function(e)

  $('addCourseForm').addEvent('submit', function(e)
    {
      e = new Event(e).stop();

      var url = 'new/ajax_class.php';

      var request = new Json.Remote(url,
        {
          onComplete: function(data)
            {

              var countColor = 0;

              if(data.error) alert(data.error);
              else
              {

              $('addCourse').className = 'inputOff';
              $('addCourse').value = "XXXX-XXX-XX";

              count = data.courseId.replace('-', '').toInt();

              //-- Check to make sure it doesn't already exist

                var repeat = new Array();
                var foundCourse = false;

                data.courseInfo.each( function(s)
                  {
                    repeat[s.section.toInt()] = s.section;
                  });

                $$('.courseSectionD').each(function( div )
                  {
                    if(div.courseId == data.courseId)
                    {
                      repeat[div.info.section.toInt()] = div.info.section;
                      colorCount = div.countUp;
                      
                      foundCourse = true;
                    }
                  });

                repeat.sort(function(a,b){return a - b});

                repeatBool = new Array();

                repeat.forEach(function(e){ repeatBool[e.toInt()] = true; });

                $$('.courseSectionD').each(function( div )
                  {
                    if(div.courseId == data.courseId)
                      repeatBool[div.info.section.toInt()] = false;
                  });

              //-- Start adding stuff

                if( foundCourse != true )
                {

                  colorCount = countUp;
                  countUp++;

                  //-- Add a main div

                    var main = new Element('div',
                      {
                        'styles' :
                          {
                            'background-color' : colorH[colorCount % ( colorH.length - 1 )]
                          },
                        'class' : 'courseWrapper',
                        'id' : 'cW' + count
                      } ).addClass('cW' + data.courseId);

                    main.colorId = colorCount % ( colorH.length - 1 );

                  //-- Text for inside the draggable section

                    var titleC = new Element('div',
                      {
                        'class' : 'courseTitleC',
                      } ).setHTML( data.courseName + ' (' + data.courseId + ')' );


                  //-- Add div for the course title

                    var title = new Element('div',
                      {
                        'styles' :
                          {
                            'background-color' : colorH[colorCount % ( colorH.length - 1 )]
                          },
                        'class' : 'courseTitle',
                        'title' : data.courseName + ' :: ' + data.courseId
                      } ).addClass( 'courseTitle' + count );

                    title.colorId = colorCount % ( colorH.length - 1 );

                    title.addClass('tips');

                    titleC.injectInside( title );


                  //-- Add the drop-down arrow

                    var titleA = new Element('div',
                      {
                        'styles' :
                          {
                            'background-color' : colorH[colorCount % ( colorH.length - 1 )]
                          },
                        'class' : 'courseArrow'
                      } ).addClass('courseArrow' + count);

                    titleA.colorId = colorCount % ( colorH.length - 1 );

                    titleA.courseId = count;

                    var titleAImg = new Element('img',
                      {
                        'src' : 'arrow.gif'
                      } );

                    titleA.addEvent('click', function(e)
                      {

                        $$('#courseOptions div').each( function(div) { div.getFirst().setStyle('display', 'none'); } );

                        $('courseO' + ( titleA.colorId.toInt() + 1) ).getFirst().setStyle('display', 'block');

                        $('courseOptions').courseId = titleA.courseId;
                        $('courseOptions').setStyle('display', 'block');
                        $('courseOptions').setStyle('left', titleAImg.getPosition().x - 84);
                        $('courseOptions').setStyle('top', titleAImg.getPosition().y + 12);
                      });

                    titleAImg.injectInside( titleA );
                    titleA.injectInside( title );

                }
                 else
                {
                }

              //-- Add a div for each section

                data.courseInfo.each( function(s)
                  {

                    if(repeatBool[s.section.toInt()] == true)
                      {

                        var timesOutput = '';

                        countS = s.section.toInt();

                        //-- Printable times

                          s.times.each(function(t)
                            {
                              if(t.output != undefined)
                              {
                                if(timesOutput != '')
                                  timesOutput += "<br />";

                                  timesOutput += t.output;
                              }
                            } );

                        //-- Static section title that stays in place

                          var sectionT = new Element('div',
                            {
                              'id' : 'sT' + data.courseId + 's' +countS,
                              'class' : 'courseSection',
                              'title' : data.courseName + ' :: ' + data.courseId + '-' + s.section + '||{' + s.prof + '}||' + timesOutput
                            } );

                          sectionT.colorId = colorCount % ( colorH.length - 1 );

                          sectionT.addClass('tips');
                     
                          sectionT.countS = countS;
                          sectionT.count = count;

                        //-- Text for inside the draggable section

                          var sectionDContent = new Element('div',
                            {
                              'id' : 'sDC' + data.courseId + 's' +countS,
                              'class' : 'courseSectionDC',
                            } ).setHTML( 'Section ' + s.section + ' - ' + s.prof.replace('<br />', ", ") );

                        //-- Draggable section title

                          var sectionD = new Element('div',
                            {
                              'styles' : 
                                {
                                  'background-color' : colors[colorCount % ( colors.length - 1 )],
                                  'top' : sectionT.getStyle('top'),
                                  'left' : sectionT.getStyle('left')
                                },
                              'id' : 'sD' + data.courseId + 's' +countS,
                              'class' : 'courseSectionD',
                              'title' : ''
                            } ).addClass('courseSectionD' + count);

                          sectionD.colorId = colorCount % ( colorH.length - 1 );

                          sectionD.addClass('drag' + count);
                          sectionD.countS = countS;
                          sectionD.count = count;

                        //-- Add text to draggable section

                          sectionDContent.injectInside( sectionD );

                        //-- Add info to the draggable section

                          //-- Section information
                            sectionD.info = s;

                          //-- Colors
                            //sectionD.color = colors[colorCount % ( colors.length - 1 )];
                            //sectionD.colorH = colorH[colorCount % ( colors.length - 1 )];
                            sectionD.countUp = colorCount;

                          //-- Course Id and name
                            sectionD.courseId = data.courseId;
                            sectionD.courseName = data.courseName;

                          //-- Add mouse enter event for section
                              sectionT.addEvent('mouseover', function(e)
                                {
                                  $( 'cW' + sectionT.count ).fireEvent('mouseenter');

                                  stop = false;

                                  if(! dragging)
                                  s.times.each(function(t)
                                    {
                                      //-- "TBA" or "online"?
                                        if(t.output == "TBA" || t.output == "online")
                                          stop == true;

                                      //-- Get the difference

                                        var d = t.end - t.start;

                                      //-- Create a preview
                                
                                        var prevTxt  = '<b>' + sectionD.courseName + '</b><br />';
                                            prevTxt += sectionD.info.prof + '<br /><br />';
                                            prevTxt += t.location + '<br />';
                                            prevTxt += sectionD.courseId + '-' + sectionD.info.section;

                                        var prev = new Element('div',
                                          {
                                            'styles' :
                                              {
                                                'background-color' : colors[sectionD.colorId],
                                                'height' : (((d / 50) * 22) - 13)
                                              },
                                            'class' : 'sCourseHover'
                                          } ).setHTML( prevTxt );

                                        prev.colorId = sectionD.colorId;

                                        //-- Add classes to preview

                                          prev.addClass('prev' + sectionD.courseId);

                                        //-- Add info to preview

                                          //prev.color  = sectionD.color;
                                          //prev.colorH = sectionD.colorH;

                                        //-- Add to the schedule
                                          if($(t.day + t.start))
                                            prev.injectInside($(t.day + t.start));

                                    });
                                });

                          //-- Add mouse leave event for section

                              sectionT.addEvent('mouseout', function(e)
                                {
                                  $$('.prev' + sectionD.courseId).each(function(div)
                                    {
                                      if(! dragging)
                                        div.remove();
                                    } );

                                });

                          //-- Add section drag into static

                                sectionD.injectInside( sectionT );

                          //-- Add section static to main div

                              rIndex = repeat.indexOf(s.section);

                              if( foundCourse == true )
                                if(rIndex == 0)
                                  sectionT.injectInside( $$('.cW' + sectionD.courseId )[0] ); //-- CHANGE!
                                else
                                  sectionT.injectAfter( $('sT' + sectionD.courseId + 's' + repeat[repeat.indexOf(s.section) - 1].toInt()).getParent() ); //-- CHANGE!!! 
                              else
                                sectionT.injectInside( main );

                              if(foundCourse)
                                var sliderFx = new Fx.Slide( sectionT ).hide( ).slideIn( );

                          //-- Add double click event for dragable section title

                              sectionD.addEvent('dblclick', function(e)
                                {
                                  //-- Generates an error sometimes
                                  //sectionD.fireEvent('mousedown', e);
                                });

                          //-- Make Draggable

                              var drop = $('content');
                              var borderFx = $('schedule_content').effect('background-color', {wait: false});
                              var dropFx = $('content').effect('background-color', {wait: false});
                              var dummyFx = $('content').effect('color', {duration: 50, wait: false});

                              sectionD.addEvent('mousedown', function(e)
                                {
                                  e = new Event(e).stop();

                                  var clone = this.clone()
                                    .setStyles(this.getCoordinates()) // this returns an object with left/top/bottom/right, so its perfect
                                    .setStyles({'opacity': 0.7, 'position': 'absolute'})
                                    .addClass('courseSectionDOn')
                                    .addEvent('emptydrop', function()
                                      {
                                        this.remove();

                                        dragging = false;

                                        //-- Remove previews

                                          $$('.prev' + sectionD.courseId).each(function(div)
                                            {
                                              div.remove();
                                            } );

                                        //-- Fire mouseleave event for Course Wrapper

                                          $( 'cW' + sectionD.count ).fireEvent('mouseleave');

                                        drop.removeEvents();

                                      }).inject(document.body);

                                    drop.addEvents(
                                      {
                                        'drop': function()
                                          {

                                            dragging = false;
                                            if(drop)
                                              drop.removeEvents();
                                            if(clone)
                                              clone.remove();

                                            //-- This is really hackish, but otherwise mootools throws an error when alert() is used

                                            dummyFx.start('000000').chain( function()
                                              {

                                                //-- Check if overlapping (MOVE UP!)

                                                  var timesArray = new Array();
                                                  var courseArray = new Array();

                                                  var overlap = false;

                                                  //-- Get all the times on the schedule

                                                    $$('.sCourseOn').each(function(div)
                                                      {
                                                        timesArray.extend(div.times.array);
                                                        courseArray.extend(div.timesCid.array);
                                                      });

                                                  //-- Get all the days

                                                    var collisions = new Array();

                                                    sectionD.info.times.each(function(t)
                                                      {

                                                        //-- Every half hour of that time

                                                          for(i = t.start.toInt(); i < t.end.toInt(); i += 50)
                                                            {
                                                              //-- Leading 0 if needed

                                                                  iS = i;

                                                                  if( i.toInt() < 1000 )
                                                                    iS = "0" + iS;

                                                                  iS = t.day + iS.toString();

                                                              //-- Is it in the timesArray?

                                                                if(timesArray.contains(iS) && courseArray[timesArray.indexOf(iS)] != sectionD.courseId)
                                                                  collisions.include(courseArray[timesArray.indexOf(iS)]);
                                                            }
                                                      });
                                                //-- Have user confirm overlaps

                                                  var overwrite = true;

                                                  if(collisions.length > 0)
                                                    {

                                                      var confirmText = '';

                                                      collisions.each( function(val)
                                                        {

                                                          confirmText += '\n  Remove ' + val;

                                                        });

                                                      overwrite = confirm( 'There are conflicts with your schedule!\n\nDo you want to do the following actions?\n' + confirmText + '\n\n  Replace with ' + sectionD.courseId );
                                                    }

                                                //-- Clean up

                                                  //-- Fire mouse out event for course wrapper

                                                    $( 'cW' + sectionD.count ).fireEvent('mouseleave');

                                                  //-- Remove previews

                                                    $$('.prev' + sectionD.courseId).each(function(div)
                                                      {
                                                        div.remove();
                                                      } );

                                                //-- Only do the following if the user doesn't cancel it

                                                  if (overwrite)
                                                    {


                                                      //-- Remove collisions

                                                        collisions.each( function(val)
                                                          {
                                                            $$('.id' + val).each( function(div)
                                                              {
                                                                div.remove();
                                                              });
                                                          });

                                                      //-- Remove others of the same course

                                                        $$('.id' + sectionD.courseId).each(function(div)
                                                          {
                                                            div.remove();
                                                          });

                                                      //-- Add to schedule

                                                        sectionD.info.times.each(function(t)
                                                          {

                                                            //-- Find difference

                                                              var d = t.end - t.start;

                                                            //-- Add to schedule

                                                              var courseTxt  = '<b>' + sectionD.courseName + '</b><br />';
                                                                  courseTxt += sectionD.info.prof + '<br /><br />';
                                                                  courseTxt += t.location + '<br />';
                                                                  courseTxt += sectionD.courseId + '-' + sectionD.info.section;

                                                              var course = new Element('div',
                                                                {
                                                                  'styles' :
                                                                    {
                                                                      'background-color' : colors[sectionD.colorId],
                                                                      'border-color' : colorH[sectionD.colorId],
                                                                      'height' : (((d / 50) * 22) - 13),
                                                                      'z-index' : ( 100 - t.start / 50 ) + 500
                                                                    },
                                                                  'class' : 'sCourseOn'
                                                                } ).setHTML( courseTxt );

                                                              course.colorId = sectionD.colorId;

                                                              course.height = (((d / 50) * 22) - 13);

                                                              var removeC = new Element('div',
                                                                {
                                                                  'styles' :
                                                                    {
                                                                      'background-color' : colorH[sectionD.colorId],
                                                                      'display': 'none',
                                                                    },
                                                                  'class' : 'sCourseRemove' 
                                                                } ).setHTML( 'X' );

                                                              removeC.courseId = sectionD.courseId;
                                                              removeC.injectInside( course );
                                                              removeC.addClass( 'sCR' + sectionD.courseId );
                                                              removeC.addClass( 'sCRC' + sectionD.courseId.replace('-', '').toInt() );

                                                              //-- Show remove button on mouse over

                                                                course.addEvent('mouseenter', function(e)
                                                                  {
                                                                    $$('.sCR' + sectionD.courseId).each( function(div)
                                                                      {
                                                                        div.setStyle('display', 'block');
                                                                        div.getParent().setStyle('min-height', div.getParent().height );
                                                                        div.getParent().setStyle('height', '');

                                                                      });

                                                                  });

                                                                course.addEvent('mouseleave', function(e)
                                                                  {
      
                                                                    $$('.sCR' + sectionD.courseId).each( function(div)
                                                                      {
                                                                        div.setStyle('display', 'none');
                                                                        div.getParent().setStyle('height', div.getParent().height );
                                                                        div.getParent().setStyle('min-height', '');

                                                                      });
      
                                                                  });

                                                              //-- Get a list of all the times this class covers
    
                                                              var jsonStringDay = '';
                                                              var jsonStringCid = '';
    
                                                                sectionD.info.times.each(function(st)
                                                                  {
    
                                                                    //-- Every half hour of that time

                                                                      for(i = st.start.toInt(); i < st.end.toInt(); i += 50)
                                                                        {

                                                                          //-- Adds leading 0 if needed

                                                                            iS = i;

                                                                            if( i.toInt() < 1000 )
                                                                              iS = "0" + iS;

                                                                            iS = iS.toString();

                                                                            jsonStringDay += ',"' + st.day + iS + '"';
                                                                            jsonStringCid += ',"' + sectionD.courseId + '"';

                                                                        }
                                                                 });

                                                              course.times = Json.evaluate('{array:[' + jsonStringDay.substr(1) + ']}');
                                                              course.timesCid = Json.evaluate('{array:[' + jsonStringCid.substr(1) + ']}');

                                                              course.addClass('id' + sectionD.courseId);
                                                              course.addClass('cS' + sectionD.courseId.replace('-', '').toInt());
                                                              course.addClass('time' + t.day + t.start);

                                                              if($(t.day + t.start))
                                                                course.injectInside($(t.day + t.start));

                                                          });

                                                          $$('.sCR' + sectionD.courseId).each( function(div)
                                                            {
                                                              div.addEvent('click', function(e)
                                                                {

                                                                  //-- Remove others of the same course

                                                                    $$('.id' + div.courseId).each(function(dd)
                                                                      {
                                                                        dd.remove();
                                                                      });
                                                                });
                                                            });


                                                      //sectionD.injectInside( $( 'sT' + sectionD.countS ) );
                                                      //sectionD.setStyle('z-index', 10);

                                                      //-- Animations

                                                        dropFx.start('EFEFEF').chain(dropFx.start.pass('ffffff', dropFx));
                                                        borderFx.start('3F3F3F').chain(borderFx.start.pass('ffffff', borderFx));
                                                    }
                                              });
                                          },

                                        'over': function()
                                          {
                                            dropFx.start('F6F6F6');
                                            borderFx.start('AFAFAF');
                                          },
                                        'leave': function()
                                          {
                                            borderFx.start('ffffff');
                                            dropFx.start('ffffff');
                                          }

                                }) ;
 
                              var drag = clone.makeDraggable(
                                {
                                  droppables: [drop]
                                });
 
                              drag.start(e); // start the event manual
                              dragging = true;

                              if(arguments[0].type == "dblclick")
                                drop.fireEvent('drop');
                          });

                      }

                  } );

                //-- Only do this stuff if new course

                  if( foundCourse != true )
                    {

                      //-- Extra div for sliding in

                        var slide = new Element('div',
                          {
                          'styles' :
                            {
                              'background-color' : colorH[colorCount % ( colorH.length - 1 )]
                            },
                            'class' : 'slider',
                          } ).addClass('slider' + count);

                          slide.colorId = colorCount % ( colorH.length - 1 );

                      //-- Add everything to the main project

                        title.injectTop(slide);
                        main.injectInside(slide);
                        slide.injectInside('courses');
                  
                      //-- Slide in

                        var sliderFx = new Fx.Slide( slide ).hide( );

                        sliderFx.slideIn( ).chain(function()
                          {
                            slide.getParent().setStyle('height', '');
                          });

                      //-- Fade others out on mouseenter

                        main.addEvent('mouseenter', function(e)
                          {
                            $$('.id' + data.courseId).each(function(div)
                              {
                                if(! dragging)
                                  div.setStyle('opacity', 0.25);
                             } );
                          } );

                      //-- Fade others back in on mouseleave

                        main.addEvent('mouseleave', function(e)
                          {
                            $$('.id' + data.courseId).each(function(div)
                              {
                                if(! dragging)
                                  div.setStyle('opacity', 1);
                              } );
                          } );
                    }


                      //-- Add tooltips for the section

                        tips = new Tips( $$('.tips'), { maxTitleChars: 700, hideDelay:110 } );

                      //-- Remove the tooltips class

                       $$('.tips').each(function(div)
                         {

                           div.removeClass('tips');

                         });
                
              }
            },
            onFailure: function(data)
              {
                alert('The information could not be loaded\n\rPlease try again later');
              }
        } ).send($('addCourse').value);
    } );

  //--------------------------
  //-- Add Course Field On/Off
  //--------------------------

    $('addCourse').addEvent('focus', function(e)
      {
        if($('addCourse').value == "XXXX-XXX-XX")
          $('addCourse').value = "";

        $('addCourse').className = 'inputOn';
            
      });

    $('addCourse').addEvent('blur', function(e)
      {
        if($('addCourse').value == "")
          $('addCourse').value = "XXXX-XXX-XX";

        if($('addCourse').value == "XXXX-XXX-XX")
          $('addCourse').className = 'inputOff';
        else
          $('addCourse').className = 'inputOn';
            
      });

    $('addCourse').fireEvent('blur');

  //--------------------------
  //-- Add Login On/Off
  //--------------------------

    $('login_username').addEvent('focus', function(e)
      {
        $('login_username').className = 'inputOn';
            
      });

    $('login_username').addEvent('blur', function(e)
      {
        if($('login_username').value == "")
          $('login_username').className = 'inputOffUsername';
        else
          $('login_username').className = 'inputOn';
            
      });

    $('login_username').fireEvent('blur');


    $('login_password').addEvent('focus', function(e)
      {
        $('login_password').className = 'inputOn';
            
      });

    $('login_password').addEvent('blur', function(e)
      {
        if($('login_password').value == "")
          $('login_password').className = 'inputOffPassword';
        else
          $('login_password').className = 'inputOn';
            
      });

    $('login_username').fireEvent('blur');

} );