/* 
 * This is the sambol js file
 */

/**
 * modal
 *
 * add a modal dialog to the DOM
 *
 * @param <string> jQuery selector for parent
 * @param <int> width in pixels
 * @param <string> content to fill with
 * @param <function> callback to run after content added
 * @param <fucntion> callback fired after modal closed
 *
 * @return <void>
 */
function modal(parent, width, content, callback, destructor) {

    
    $(parent).append('<div id="darken" class="modal">&nbsp;</div>');

    var theIndex = (parseFloat($(parent).css('z-index')) || 1000);

    var data;//this is used to hold data returned from callback

    var pHeight = (parent != 'body') ? $(parent).height() : $(document).height();

    $('#darken').css({

        width: $(parent).outerWidth(),
        height: pHeight,
        zIndex:  theIndex + 5
        
    });

    if (parent == 'body') {

        $(window).bind('resize', function() {

            $('#darken').css('height', $(document).height());

        });

    }


    $(parent).append('<div id="modal" class="modal"><div id="close" style="border: 2px solid black;">&nbsp;</div>'+content+'</div>');

    sizeModal(parent, width, theIndex);

    $('#modal #close').unbind().bind('click', function() {

        $('.modal').fadeOut('slow', function(){

            $('.modal').remove();

            if (typeof(destructor) == 'function') {

               var p = $(parent).get(0);

               destructor.call(p, data);

               destructor = null;//need to do this do it is not called multiple time. Not sure why??

            }

        });

    })
    .hover(
        function() {$(this).css('border', '2px solid red')},
        function() {$(this).css('border', '2px solid black')}
     );


     if (typeof(callback) == 'function') {

        data = callback();

     }

     $('#modal').bind('modalResize', {'width': width, 'parent': parent, 'index': theIndex}, function (e) {

           sizeModal(e.data.parent, e.data.width, e.data.index);

     });

}

function sizeModal(parent, width, theIndex) {

    var parentHeight = (parent != 'body') ? $(parent).height() : $(window).height();

    var offset = (parent != 'body') ? $(parent).scrollTop() : $('body').scrollTop();

    $('#modal').css({

        'width': width,
        padding: '5px',
        position: 'absolute',
        left: Math.round(($(parent).width() - width) / 2),
        top: Math.round((parentHeight - $('#modal').height()) / 2) +  offset,
        border: '2px solid black',
        background: 'white',
        zIndex: theIndex + 10,
        display: 'none'

    }).fadeTo('slow', .9);
    

}

//ad wait icon to page
function addWait(element) {

   if (!$(element).is('*')) element = 'body';

   if (element == null) {

       element = '#ajax_box';
   }

   var offset = (element != 'body') ? $(element).scrollTop() : $('body').scrollTop();

   var theHeight = (element != 'body') ? $(element).outerHeight() : $(window).height();

   var pos = $(element).position();

   $(element).append('<div id="wait_back"></div>')

   $('#wait_back').css({

       position: 'absolute',
       height: theHeight,
       width: $(element).outerWidth(),
       top: offset,
       left: 0

   }).append('<div id="indicator">&nbsp;</div>');


   $('#wait_back #indicator').css({

       position: 'absolute',
       top: Math.round((theHeight / 2)) - 32,
       left: Math.round(($('#wait_back').outerWidth() /2)) - 32

   });

   if (element == 'body') {

       $(window).bind('resize', function() {

           $('#wait_back').css({

              width: $(window).width(),

              height: $(window).height() + $('body').scrollTop()

           });


       })

   }
   

}

function removeWait() {

   $('#wait_back').remove();

}


function checkActive() {

    if ($('input#active:checked').is('*')) {

        //item is active just make sure stuff set

        $('#theEditor').css('border', '1px solid black');
        $('#theEditor .alert').text('');
        $('#active_label').css({color: 'black', fontWeight: 'normal'});

    }else{
        //item not active allert status
        $('#theEditor').css('border', '1px solid red');
        $('#theEditor .alert').text('!!Page inactive, will not display.');
        $('#active_label').css({color: 'red', fontWeight: 'bold'});

    }

}

function statusUpdate(msg) {

    $('#status').text(msg).fadeIn('slow');

    setTimeout(function(){

            $('#status').fadeOut('slow', function () {
                
                $(this).text('');
                                
                
            });


}, 2500);

}


function moveup () {

     //move up item in front promo list so extra space is removed
    $('.moveup').each(function() {

        var ammount = $(this).parent().find('div.promo_item div').css('top');

        if (ammount != null) {

             var mod = parseFloat(ammount.replace('px', ''));

            $(this).css('margin-top', (mod + 40) + 'px');

        }

        ammount = null;

    });

}


$(function() {

    $('#content #left').css({width:'600px', height: '244px'}).cycle({speed: 2000, timeout: 6000, delay: 500});

    var seg = window.location.pathname;

    //create active tab for current menu item
    $(".menuBar a[href$="+seg+"]:not(.nogo)").css('background', 'url(/rsc/img/menuback_roll.jpg)');

    if ($('#controlbar').is('*')) {

        $('.edit').each(function() {

               $(this).append('<div class="edit_icon">&nbsp</div>');

               //get keyword
               var component;

               var spID;

               if ($(this).hasClass('front')) {

                   component = 'front';
               }

               if ($(this).hasClass('dockitem') ) {

                   component = 'menu';

                   spID = this.id;
               }

               if ($(this).hasClass('menupage')) {

                    component = 'menu';

                    spID = this.id;

               }
               
               if ($(this).hasClass('page')) {

                   component = 'page';

                   spID = this.id;

               }

               var wWidth = $(document).width();
               var wHeight = $(document).height();

               $(this).find('.edit_icon')

               .hover(function() {

                    $(this).css('background', 'url(/rsc/img/edit_icon_roll.png)');

               },function () {

                   $(this).css('background', 'url(/rsc/img/edit_icon.png)');

               })
               .live('click', function() {

                  addWait('body');

                  if (component == 'page') {

                       /*
                        Handle page editor here

                       */
                       
                       $.post('/ajax.php', {'component':component, 'data':spID}, function(data) {

                            removeWait();

                            var RTeditor = 1;

                            $('.page').fadeOut('slow', function() {

                                $('#content').append(data);

                                $('#wysiwyg').wysiwyg();

                                checkActive();

                                $('input#save').bind('click', function() {

                                     var updatedContent = $('#wysiwyg').val();

                                     var titleVal = $('input#title').val();

                                     var DescVal = $('input#description').val();

                                     var activeVal = $('input#active:checked').val();

                                     $('#theEditor').remove();

                                     addWait();

                                     $.post('/ajax.php', {'component':component, 'data':spID, action: 'save', 'value': updatedContent, 'title': titleVal, 'description':DescVal, 'active': activeVal, 'RTeditor': RTeditor}, function(data) {

                                          removeWait();

                                          $('.page .innerContent').html(data);

                                          $('.page').fadeIn('slow');

                                          checkActive();


                                     });


                                })

                                $('input#cancel').bind('click', function() {

                                    $('#theEditor').remove();

                                    $('.page').fadeIn('slow');


                                });


                                $('input#togle').bind('click', function() {

                                        if ($('.wysiwyg').is('*')) {
                                         
                                            /*
                                             *Editor is there so remove
                                             **/

                                            $('.wysiwyg').remove();
                                            $('#wysiwyg').show().autogrow();
                                            $('#togle').val('Editor');

                                            RTeditor = 0;

                                        }else{

                                            /*
                                             *Editor not there so ad it
                                             */
                                            $('#wysiwyg').wysiwyg();
                                            $('#togle').val('Edit html');

                                            RTeditor = 1;
                                        }

                                });

                            });

                       });


                  } else {


                          $.post('/ajax.php', {'component':component, 'data':spID}, function(data) {

                                removeWait();

                                $('body').append('<div id="block_out"></div>').append(data);

                                //triger move up function
                                moveup();

                                $('#block_out').css('height', wHeight);

                                var boxWidth =  $('#ajax_box').width();

                                $('#ajax_box').css('left', Math.round((wWidth - boxWidth)/2));


                                $('#close').hover (
                                    function() {$(this).css('border', '2px solid red')},
                                    function() {$(this).css('border', '2px solid black')})
                                    .bind('click',function() {$('#ajax_box, #block_out').remove();});

                                /*
                                 * Front Promo Editor Bindings
                                 *
                                 */
                                function promoBind() {


                                    $('.promo_edit_item').each(function() {

                                        var theId = this.id.replace('id_', '');
                                        var theName = $(this).find('h3').text();
                                        var theString = $(this).find('textarea').val();
                                        var theItem = $(this);

                                        $(this).find('input[type=submit]').bind('click', function() {

                                           var set = confirm('Set Front Page Promo to: '+theName);

                                           if(set) {

                                                addWait();

                                                $.post('/ajax.php', {'component':'setfront', 'id':theId}, function(d3) {

                                                     removeWait();

                                                     if (d3.status == 'ok') {

                                                        window.location = '/';


                                                     }

                                                }, 'json');



                                           }

                                           return false;


                                        });


                                        $(this).find('textarea').bind('focusout', function () {

                                                addWait();

                                                $.post('/ajax.php', {'component':'setfronttext', 'id':theId, 'text':$(this).val()}, function(d4) {

                                                     removeWait();

                                                     if (d4.status != 'fail') {

                                                        $(this).val(d4.status);

                                                        theItem.find('.promo_item').replaceWith(d4.obj);

                                                        statusUpdate('Item id '+theId+' updated.');

                                                     }else{

                                                          $(this).empty();

                                                     }

                                                }, 'json');

                                            return false;

                                        });

                                        $(this).find('#edit_style').bind('click', function() {

                                            var content = theItem.find('.promo_item div').attr('style');

                                            modal('#ajax_box', 500, '<h3>Edit html element styles</h3><div id="st_mess"></div><textarea id="style_editor" cols="50" rows="12">'+content+'</textarea><br><input class="ind" type="submit" id="style_save" name="style_save" value="save" >', function() {

                                                $('#style_save').bind('click', function() {

                                                    var save = encodeURIComponent($('#style_editor').val());

                                                    $.post('/ajax.php', {'component': 'setfrontstyles', 'name': theName, 'styles':save}, function(data){

                                                        if (data.status != 'fail') {

                                                            theItem.find('.promo_item a div').attr('style', data.style);

                                                            $('#st_mess').css('color', 'green').text('styles updated OK');

                                                        } else {

                                                            $('#st_mess').css('color', 'red').text('styles could not be updated.');

                                                        }




                                                    }, 'json');


                                                });


                                            });


                                            return false;
                                        });

                                        $(this).find('input[name=link]').bind('focusout', function () {

                                                addWait();

                                                $.post('/ajax.php', {'component':'setfrontlink', 'id':theId, 'text':$(this).val()}, function(d5) {

                                                     removeWait();

                                                     if (d5.status != 'fail') {

                                                        $(this).val(d5.status);

                                                        statusUpdate('Item id '+theId+' updated.');

                                                     }else{

                                                          $(this).empty();

                                                     }

                                                }, 'json');

                                            return false;

                                        });



                                    });


                                }

                                promoBind();
                                 /*
                                  * Menu items section
                                  *
                                  */

                                 $('#add').bind('click', function() {

                                     addWait();

                                     $.post('/ajax.php', {'component':'menu', 'data':spID, 'what': 'addrow', 'menu':'M'}, function(data) {

                                            removeWait();

                                            statusUpdate('Item added.');

                                            $('#no_items').remove();

                                            $('table').append(data);

                                     }, 'html');

                                 })

                                 //delete button
                                 $('.del').live('click', function() {

                                     var theId = $(this).parent().parent().attr('id');

                                     var conf = confirm('Delete this Item? (id: '+theId+')');

                                     if (conf) {

                                         addWait();

                                         $.post('/ajax.php', {'component':'menu', 'data':spID, 'what': 'delrow', 'menu':'M', 'id': theId}, function(data) {

                                            removeWait();

                                           if (data.result == 1) {

                                                statusUpdate('Item '+theId+' deleted.');

                                                $('#'+theId).remove();

                                            }


                                         }, 'json');


                                     }


                                 });


                                 /*
                                  **
                                  ****Add new Front Promo Functionality *****
                                  **
                                  */
                                 $('#promoAdd').bind('click', function() {

                                    addWait();

                                    $.post('/ajax.php', {'component':'addfront', 'action':'form'}, function(data) {

                                        removeWait();

                                        modal('#ajax_box', 400, data);

                                        var ok = false;


                                        $('#addfront input[name=send]').bind('click', function () {

                                            addWait();

                                            $.post('/ajax.php', $('#addfront form').serialize(), function(data) {

                                                removeWait();

                                                if (data.status == 'ok') {

                                                     $(this).find('#modal_message').text('');


                                                     $('#edit_form').remove();

                                                     $('#inner').append(data.newlist);

                                                     promoBind();

                                                     $('.modal').remove();


                                                }else{

                                                    $(this).find('#modal_message').text(data.message);

                                                }

                                                

                                           }, 'json');


                                           return false;


                                        })

                                        $('#addfront input[name=promoname]').unbind().bind('change', function () {

                                            var curentName = $(this).val();

                                            $.post('/ajax.php', {'component':'addfront', 'action':'validatename', 'name':curentName}, function(d){

                                                if (d == 'taken') {

                                                  $('#modal_message').text('Name already in use. Please select another');

                                                  $(this).css({background: 'red'});

                                                  ok = false;

                                                } else {

                                                  $('#modal_message').empty();

                                                  $('#addfront input[name=promoname]').val(curentName);

                                                  $(this).css({background: 'white'});

                                                  ok = true;
                                                    
                                                }


                                            }, 'html');


                                         });

                                        $('#addfront #upload').bind('change', function() {

                                             $(this).upload('/ajax.php',{'component':'addfront', 'action': 'upload'}, function(data) {

                                               if (data.status == 'OK') {

                                                  var file = data.filename;
                                                 
                                                 $('#upload_message').css('color', 'green').text('File '+file+' Upload OK!');

                                                 $('input[name=tempfile]').attr('value', file);

                                                 $('input[type=file]').remove();

                                                 if (ok) {

                                                    $('.qh').show();

                                                 }
 
                                               } else {

                                                   $('#upload_message').css('color', 'red').text(data.message);


                                               }


                                            }, 'json');


                                       });

                                    }, 'html');

                                     

                                 })

                                 //handle the field
                                 $('input:not(".ind")').live('focusout', function () {

                                        var thisClass = $(this).attr('class');
                                        var theId = $(this).parent().parent().attr('id');
                                        var theValue = $(this).val();

                                        if ($(this).attr('type') == 'checkbox' ) {

                                           theValue = ($(this).attr('checked')) ? '1': 'deactivate';

                                        }

                                        if (theValue) {

                                            addWait();

                                             $.post('/ajax.php', {'component':'menu', 'data':spID, 'what': 'editrow', 'field':thisClass, 'menu':'M', 'value':theValue, 'id': theId}, function(data) {

                                                removeWait();

                                                if (data.result == 1) {

                                                    statusUpdate('Item '+theId+' updated. '+thisClass);

                                                }


                                             }, 'json');

                                        }

                                 });



                            }, 'html');

                    }

               });


        });

        //bind the image uploader for menu
        $('img.men_im_bk, em.noim').live('click', function () {

            var theId = $(this).parent().parent().attr('id');
         
                    addWait('#ajax_box');

                    $.post('/ajax.php', {'component':'menu', 'what':'imagedialog', 'id':theId}, function(d){

                        removeWait();

                        modal('#ajax_box', 400, '<div id="img_dialog">'+d+'</div>', function() {

                            var theReturn = {id: theId, action: 'none'};

                            $('#img_dialog #upload').bind('change', {'theId':theId}, function(e) {

                               addWait('#modal');

                                $(this).upload('/ajax.php', {'component':'menu', 'what':'imgupload', 'id':e.data.theId}, function(d){

                                    removeWait();

                                     if (d.status == 'ok') {

                                         $('#img_dialog div.error').css('color', 'green').text('Upload OK');

                                         $('#img_dialog div#img').empty().append('<img src="/'+d.img+'" width="225">');

                                         $('#img_dialog #commit, #img_dialog #cancel').show();

                                         $('#modal').trigger('modalResize');

                                          $('#img_dialog #commit').bind('click',{'id':e.data.theId, 'file':d.file, 'img':d.img}, function(g){

                                              addWait('#modal');

                                              $.post('/ajax.php', {'component': 'menu', 'what':'commitupload', 'id':g.data.id, 'filename':g.data.file}, function(w) {

                                                  removeWait();

                                                  if (w.status == 'ok') {

                                                      $('#img_dialog div#img').attr('src', w.img+'_sm.jpg');

                                                      $('#modal').trigger('modalResize');

                                                      $('#img_dialog div.error').css('color', 'green').text('Commited');


                                                      theReturn['action'] = 'img';
                                                      theReturn['path'] = w.img;

                                                      $('#modal #close').trigger('click');


                                                  }


                                              }, 'json');


                                          });


                                          $('#img_dialog #cancel').bind('click',{'file':d.file}, function(g){

                                               $('#modal #close').trigger('click');

                                          });


                                     }else{

                                         $('#img_dialog div.error').css('color', 'red').text(d.error);

                                     }


                                }, 'json');

                            });

                            //delete button
                              $('#im_del').bind('click',{'id':theId}, function(z) {

                                  var ok = confirm('Delete this Image?');

                                  if (ok) {

                                      addWait('#modal');

                                      $.post('/ajax.php', {'component': 'menu', 'what':'delete', 'id':z.data.id}, function(p){

                                            removeWait();

                                            if (p.status == 'ok') {

                                                $('#img_dialog #img').fadeOut('slow', function() {

                                                    $('#modal').trigger('modalResize');

                                                    $(this).empty().append('<em.Image deleted</em>').fadeIn('slow');

                                                    theReturn['action'] = 'remove';

                                                });

                                            }else{

                                                alert('could not delete image');
                                            }


                                      }, 'json');


                                  }

                              });

                          return theReturn;

                        }, function(e) {

                            /*
                             * this is the destructor method called by modal() when it is closed
                             *
                             */

                            switch(e.action) {

                                case 'img':

                                 
                                    //handle a new image
                                    $(this).find('tr#'+e.id).find('em.noim, img.men_im_bk').fadeOut('fast', function() {

                                       $(this).replaceWith('<img width="44" src="'+e.path+'_tn.jpg" class="men_im_bk">').fadeIn('slow');

                                    });



                                    break;

                                case 'remove':

                                     $(this).find('tr#'+e.id).find('img.men_im_bk').fadeOut('fast', function() {

                                         $(this).replaceWith('<em style="font-size: small;" class="noim">none</em>').fadeIn('slow');
                                     });
                                    
                                    break;

                            }

                          
                        });

                    }, 'html');

            });


            $('td.kw').live('click', function(e) {

                var theId = $(this).parent().attr('id');

                var target = e.target;

                addWait('#ajax_box');

                 $.post('/ajax.php', {'component':'menu', 'what':'keydialog', 'id':theId}, function(d){

                     removeWait();

                     modal('#ajax_box', 400, '<div id="key_dialog">'+d+'</div>', function() {

                              $('form[name=kw]').append('<input type="hidden" name="id" value="'+theId+'"><input type="hidden" name="component" value="menu"><input type="hidden" name="what" value="updatekeys">');

                              $('form[name=kw]').submit(function() {

                                  var vals = $(this).serialize();
                                  
                                  $.post('/ajax.php', vals, function(a) {

                                        $('form[name=kw]').remove();

                                        $('#key_dialog').append('<div id="k_message">Keywords updated!</div>')


                                  }, 'json');


                                  return false;
                              });

                     }, function () {

                         addWait('#ajax_box');


                         $.post('/ajax.php', {'component':'menu', 'what':'getkeys', 'id':theId}, function(d){

                           $(target).empty().append(d);

                            removeWait();

                         }, 'html');

                     });



                 }, 'html');


            });

 
    }

    $('#menuDock .dockitem .back, #general_menu .dockitem .back').hover (

      function() {
        $(this).css({background: 'gray'});

      },

      function() {
        $(this).css({background: '#ED9030'});
      }

    );

    $('#general_menu .dockitem span').each(function() {

        var h = $(this).outerHeight();

        $(this).css({marginTop: '-'+h+'px', top: h+3});

    });

    var wrapperWidth = $('#wrapper').width();

    var ieOffset = (navigator.appName == 'Microsoft Internet Explorer') ? 60 : 0;

    var genWidth = Math.round(($('#general_menu .dockitem').outerWidth(true) * 4)+ieOffset);


    $('#general_menu').css({width: genWidth, marginLeft: Math.round(((wrapperWidth - genWidth) /2)-10)});


    var menuWidth = Math.round(($('#menu .menu_item').outerWidth(true) * 2) + 10);

    $('#menu').css('width', menuWidth);

    /*
     * Ad the grad to lunch page
     *
     */
    $('#content:has(#lunch)').css({backgroundImage: 'url(/rsc/img/light-grad.jpg)', backgroundRepeat: 'repeat-x'});

    $('#mapSidebar a').attr('target', '_blank');

    //fix lunch menu table in IE
    $('table#tblMain').attr('align', 'center');

    $('#menuDock .arrowRight').hover(function(){

                             $(this).css({background: 'url(/rsc/img/arB_roll.png)', backgroundRepeat: 'no-repeat', backgroundPosition: 'center'});

                          },
                          function(){

                              $(this).css({background: 'url(/rsc/img/arB.png)', backgroundRepeat: 'no-repeat', backgroundPosition: 'center'});

                          });


    $('#menuDock .arrowLeft').hover(function(){

                         $(this).css({background: 'url(/rsc/img/alB_roll.png)', backgroundRepeat: 'no-repeat', backgroundPosition: 'center'});

                      },
                      function(){

                          $(this).css({background: 'url(/rsc/img/alB.png)', backgroundRepeat: 'no-repeat', backgroundPosition: 'center'});

                      });

    $('ul.list').find('span').each(function () {

           if ($(this).text().length > 18) {

               $(this).css({letterSpacing: '-1px'});

           }

    });


    $('.list, #general_menu').find('.back').each(function () {
    
        $(this).after('<div class="drop_shad">&nbsp;</div>');

    });


    /*
     * adjust the height of menu items that have images
     * so they do not overlap each other
     *
     */
    var dheight = parseFloat($('.menu_item').css('height'));
    
    $('.menu_item').each(function(){

        if ($(this).find('img').is('*')) {

            var newHeight = $(this).find('h3').outerHeight(true) + $(this).find('img').height();

            if (newHeight > dheight) {

                dheight = newHeight + 5;

            }

        }

    });

    $('.menu_item').css('height', dheight);


    /*
     * add hover big image for menu items
     *
     */
     $('.menu_item .menu_im')

  
     .bind('mouseover', function(e){

         var src = this.src.replace('_sm', '');
         var title = $(this).parent().parent().find('h3').text();

         modal('body', 530,

           '<h2 style="width: 530px, text-align: center; margin-top: -2px">'+title+'</h2><img style="border: 1px solid gray" src="'+src+'">'

        );

     });


     /*
      * Do some cool stuff with teh about us section on homepage
      *
      *
      */
     $('#wrapper #about p:first').css({fontSize: '18pt', lineHeight: '120%', marginBottom: '35px' }).append('<a href="" id="more">+More</a>');

     var storedHeight = $('#wrapper #about').height();

     var activeHeight = storedHeight;

     $('#about').css({height: '110px'});

     $('#wrapper #about p a#more').bind('click', function(d){

         var b = $(this);

         $('#wrapper #about').animate({height: activeHeight}, 'slow', 'linear', function() {

             var t = (b.text() == '+More') ? '-Less' : '+More';

             var h = (activeHeight == storedHeight) ? 120 : storedHeight;

             b.text(t);

             activeHeight = h;

             
         });

         return false;

     });

     $('#wrapper #social .icon').attr('target', '_BLANK');



    //the drop down menu

    $('.menuBar .dropdown')
    .before('<span id="drop">&nbsp;</span>')
    .hover(
        function() {
            
            var item = $(this).parent().find('ul.dropped');

            var pos = $(this).position();

            item.css({top: (pos.top + $(this).height()), left: pos.left, width: $(this).width()+'px'})
            .slideDown('slow', function() {

                    $(this).mouseleave(function(){

                        var slide = $(this);
                        var tmrPR;
                        if (tmrPR) {
                                clearTimeout(tmrPR);
                        }
                        tmrPR = setTimeout(function() {
                              slide.slideUp();

                        }, 200);

                    });


            });
            

           
        },
        function() {

             //$(this).parent().find('ul.dropped').slideUp();

        }
    )
    .click(function(){return false;});
    

});


