$j = jQuery.noConflict();
var basketTop;
var headline_count;
var headline_interval;
var current_headline = 0;
var old_headline = 0;
var root_url = 'http://www.dementia-signage.co.uk/';

jQuery.fn.extend({
      toggleFaq: function()
      {
         var obj = $j(this).is('li') ? $j(this)[0] : $j(this).parent().parent()[0];
         if($j(obj).is('.expanded'))
         {
            $j(obj).contractFaq();
         }
         else
         {
            $j(obj).expandFaq();
         }
      },

      expandFaq: function()
      {
         $j(this).addClass('expanded');
         $j(this).find('.answer').slideDown('fast');
         $j(this).find('.resource-center-logo').slideDown('fast');
         $j(this).find('.expand-bar').addClass('expanded-bar');
      },

      contractFaq: function()
      {
         $j(this).find('.resource-center-logo').slideUp('fast');
         $j(this).find('.answer').slideUp('fast', function()
            {
               $j(this).parent().parent().removeClass('expanded');
            });
         $j(this).find('.expand-bar').removeClass('expanded-bar');         
      }
   });

function resetBasketTop()
{
   basketTop = $j('#basket').offset().top;
}

function goForward()
{
    document.customerform.proceed.value = "true";
    document.customerform.submit();
}

function goBack()
{
    document.customerform.proceed.value = "false";
    document.customerform.submit();
}

function addRemToBasket(price, ref, name, imgsrc)
{    
            /*if($j(this).parent().children('.alt-images') && ($j(this).parent().parent().attr('id') == 'product-2'))
            {
               var specificNumber = ($j(this).parent().parent().children('.alt-images').children('.current').attr('id').split('-'));
               specificNumber = specificNumber[specificNumber.length - 1];
               ref = ref + specificNumber;
            }*/

            /*
            if($j(this).next().is('.select-color'))
            {
               ref += $j(this).next().children('select').val();
               name += " ("+$j(this).next().children('select').children('option:selected').text()+")";
            }
            */
            
            $j.post("api/cart.php?action=addProduct",
               {ref: ref, description:name, price:price, imgsrc: imgsrc},
               function(data) 
               {
                  flashBasketAndData(data);
                  //$j('#basket-container').html(data);
               });

            return false;
 }
         
         var greyboxopen = 0; // lock to stop multiple greyboxes from opening
         
         function GB_Close()
         {
            greyboxopen = 0;
         }
         
 function headline_rotate() {
   current_headline = (old_headline + 1) % headline_count; 
   $j("div.scroll-news-item:eq(" + old_headline + ")").animate({top: -205},"slow", function() {
     $j(this).css('top','210px');
   });
   $j("div.scroll-news-item:eq(" + current_headline + ")").show().animate({top: 5},"slow");  
   old_headline = current_headline;
 }


        
$j(document).ready(function()
   {     
       $j('#slideshow').cycle({
            fx: 'fade',
            speed: 1000,
            timeout: 10000
       });

       $j('marquee').marquee();
       headline_count = $j("div.scroll-news-item").size();
       $j("div.scroll-news-item:eq(" + current_headline + ")").css('top', '5px');
       
       headline_interval = setInterval(headline_rotate,15000); //time in milliseconds
/*
        $j('#menu-container ul > li > a')
		.mouseover(function(){
            $j(this).parent().css( {backgroundPosition: "0px -250px"} )
			$j(this).parent().stop().animate({backgroundPosition:"(0px 0px)"}, {duration:300})
		})
		.mouseout(function(){
			$j(this).parent().stop().animate({backgroundPosition:"(0px -250px)"}, {duration:160, complete:function(){
				$j(this).parent().css({backgroundPosition: "0px -250px"})
			}})
		});

          
    $j('#menu li li:not(".divider")').mouseover(function(){
                //$j(this).highlightFade({start:'#3a3a3a',end:'#777',speed:100,iterator:'exponential'})

                $j(this).stop().animate({backgroundColor: "#777"}, 200);

                //$j(this).stop().css("background", "#777");
               })
                .mouseout(function() {
                $j(this).stop().animate({backgroundColor: "#3a3a3a"}, 200);
     });
 
 */
 
      $j(".signage-table img").click( function() {
            if(greyboxopen == 0)
            {
              greyboxopen = 1;
              GB_showCenter("View Sign",root_url + "view-product.php?items=" + $j(this).attr('items'),260,350, GB_Close);
              return false;
             }
             
            return false;
          });
 
 
       $j('#checkout-cart-button').click( function() {  window.location = "orderDetails.php" });

      $j('#tabs > ul').tabs({ cache: true });
      $j('#tabs > ul').tabs({ ajaxOptions: { async: false } });
	  $j('.ui-tabs-nav').bind('tabsload', function(event, ui) {       
          $j("a.greybox").click(function(){
                var t = this.title || this.innerHTML || this.href;

                if(greyboxopen == 0)
                {
                  greyboxopen = 1;
                  GB_showCenter(t,this.href,500,450, GB_Close);
                  return false;
                 }
                 
                return false;
              });       
      });
      
      $j('#design-considerations').accordion({autoheight:false});
      $j('#design-considerations').livequery('click', function()
         {
            setTimeout(resetBasketTop, 500);
         });
        
         if($j('#basket').length > 0)
            basketTop = $j('#basket').offset().top;

     if(isIE6)
      {
         $j('#basket-contents li').livequery('mouseover', function()
            {
               $j(this).children('.image').show();
            });
         $j('#basket-contents li').livequery('mouseout', function()
            {
               $j(this).children('.image').hide();
            });
      }

      $j(window).scroll(function()
         {
            if($j(window).scrollTop() + 10 > basketTop)
            {
               $j('#basket').addClass('fixed-basket');
               if(isIE6) $j('#basket').css('margin-top', $j(window).scrollTop() + 30 - basketTop);
            }
            else
            {
               if($j('#basket').is('.fixed-basket')) $j('#basket').removeClass('fixed-basket');
               if(isIE6) $j('#basket').css('margin-top', '0');
            }
         });

      $j('.alt-images a').click(function()
         {
            var thisNumber = $j(this).attr('id').split('-');
            thisNumber = thisNumber[thisNumber.length - 1] - 1;
            $j(this).parent().parent().children('div.image').children('img').css('margin-left', -thisNumber*170 + 'px');
            $j(this).parent().children('.current').each(function()
               {
                  var thisNumber = $j(this).attr('id').split('-');
                  thisNumber = thisNumber[thisNumber.length - 1];
                  $j(this).removeClass('alt-image-'+thisNumber+'-current');
                  $j(this).removeClass('current');
               });
            $j(this).addClass('current');
            $j(this).addClass('alt-image-'+(thisNumber+1)+'-current');
            return false;
         });

      $j('.price-button').livequery('click', function()
         {
            var price = $j(this).find('.price').html().substr(1);
            price = parseInt(price);
            var ref = $j(this).find('.reference strong').html();
            
            var name = $j(this).parent().parent().prev().html();

            /*if($j(this).parent().children('.alt-images') && ($j(this).parent().parent().attr('id') == 'product-2'))
            {
               var specificNumber = ($j(this).parent().parent().children('.alt-images').children('.current').attr('id').split('-'));
               specificNumber = specificNumber[specificNumber.length - 1];
               ref = ref + specificNumber;
            }*/

            
                
            /*
            //original code doesnt work for multiple items, only a single one
            if($j(this).next().is('.select-color'))
            {
          
               ref += $j(this).next().children('select').val();
               name += " ("+$j(this).next().children('select').children('option:selected').text()+")";
            }
            */
                
            var color = $j(this).parent().parent().find('.select-color').children('select').children('option:selected').val();
            if(color)
            {
                ref += '-' + color;
                name += " (" + $j(this).parent().parent().find('.select-color').children('select').children('option:selected').text() + ")";
            }
            
            // Check for specific link first
            var linkId = $j(this).attr('id');
            if(linkId != ''){
                var imgsrc = $('img.' + linkId).attr('src');
            }else{
                var imgsrc = $j(this).parent().parent().find('img').attr('src');
            }
            //alert($j(this).parent().parent().html());
            name = name.replace("°","&ordm;"); // fix degree symbols
            $j.post("api/cart.php?action=addProduct",
               {ref: ref, description:name, price:price, imgsrc: imgsrc},
               function(data) 
               {
                  flashBasketAndData(data);
                  //$j('#basket-container').html(data);
               });

            return false;
         });

      $j('#clear-cart-button').livequery('click', function()
         {
            if(confirm("Are you sure you want to clear your cart?"))
            {
               $j.post("api/cart.php?action=clearCart", {},
                  function(data) 
                  {
                     flashBasketAndData(data);
                     //$j('#basket-container').html(data);
                  });
            }
         });
         
      $j('#edit-cart-button').livequery('click', function()
         {
                if(!$j('#basket-container').find('.total').html())
                {
                    alert("Your basket is empty.");
                }
                else
                {
                    window.location = root_url + "editCart.php";
                }
         });
         
      $j('#save-cart-button').livequery('click', function()
         {
            var response = '';
            var count = 0;
            $j('.edit-quantity').each(function()
               {
                  response += $j(this).val() + ",";
                  count++;
               });
            $j.post('api/cart.php?action=editCart',
               {
                  response:response
               },
               function(data)
               {
                  $j('#edit-cart-content').html(data);
               });
         });
         
      $j('.edit-remove').livequery('click', function()
         {
            $j(this).parent().prev().fadeOut();
            $j(this).prev().children('input').val('0');
            $j(this).parent().fadeOut();
         });

      $j('ul:not(.expanded-boxes) .answer').hide();
      $j('ul:not(.expanded-boxes) .resource-center-logo').hide();
      $j('ul:not(.expanded-boxes) .answer').after('<a href="javascript:void(0)" class="expand-bar"></a>');
      $j('.expand-all').livequery('click', function()
         {
            if($j(this).is('.expanded'))
            {
               $j('.faqs li').each(function() { $j(this).contractFaq() });
               $j(this).removeClass('expanded');
               $j(this).html( ($j(this).is('#expand-all-faqs') ? 'click here to show all the answers':'click here to show all the stories') );
            }
            else
            {
               $j('.faqs li').each(function() { $j(this).expandFaq() });
               $j(this).addClass('expanded');
               $j(this).html( ($j(this).is('#expand-all-faqs') ? 'click here to hide all the answers':'click here to hide all the stories') ); 
            }
         });
      $j('.faqs:not(.expanded-boxes) li:not(.expanded), .faqs li.expanded .expanded-bar, .links li:not(.expanded), .links li.expanded .expanded-bar').livequery('click', function()
         {
            $j(this).toggleFaq();
         });

      $j('.flags li').livequery('click', function()
         {
            $j('.flags li.current').removeClass('current');
            $j(this).addClass('current');
            var country = $j(this).attr('id').split('-');
            country = country[country.length - 1];
            $j('.contact-details').hide();
            $j('#contact-details-'+country).show();
         });

      $j('#hear-about select').livequery('change', function()
         {
            if($j(this).val() == "Other")
            {
               $j('#hear-about-other').slideDown('fast');
            }
            else
            {
               $j('#hear-about-other').slideUp('fast');
            }
         });

      $j('#hear-about select').livequery('keyup', function()
         {
            if($j(this).val() == "Other")
            {
               $j('#hear-about-other').slideDown('fast');
            }
            else
            {
               $j('#hear-about-other').slideUp('fast');
            }
         });  


        $j("ul.sf-menu").superfish();       

      $j('#contact-form').livequery('submit', function()
         {
            if(
               $j('input[@name=name]').val() &&
               $j('input[@name=email]').val() &&
               $j('input[@name=telephone]').val() &&
               $j('textarea[@name=address]').val() &&
               $j('textarea[@name=message]').val() &&
               $j('select[@name=hear-about]').val() != "")
            {
               return true;
            }
            else
            {
               alert("Please fill out all the boxes on the contact form before sending your enquiry.");
               return false;
            }
         });
         
         $j('#enquiry-form').livequery('submit', function()
         {
            if(
               $j('input[@name=name]').val() &&
               $j('input[@name=email]').val() &&
               $j('input[@name=telephone]').val() &&
               $j('textarea[@name=message]').val())
            {
               return true;
            }
            else
            {
               alert("Please fill out all the boxes on the contact form before sending your enquiry.");
               return false;
            }
         });
      
      // Swatches
      var imgOrig;
      $j('a.swatch').livequery('mouseover',function() {
        var img = $(this).parent().parent().find('img:first');
        imgOrig = img.attr('src');
        img.attr('src', $(this).attr("rel"));
        }).livequery('mouseout',function(){
            var img = $(this).parent().parent().find('img:first');          
            img.attr('src', imgOrig);    
        });
      $j('a.swatch').livequery('click',function(){
        var img = $(this).parent().parent().find('img:first');
        img.attr('src', $(this).attr("rel"));
        imgOrig = $(this).attr("rel");
        var arrCodes = $(this).html().split('-');        
        var arrRef = $(this).parent().parent().parent().find('.reference strong');
        $j.each(arrRef,function(zz,arr){
            $(this).html(arrCodes[zz]);    
        });
          return false;
      });  
   });

function flashBasket()
{
   $j('#basket').animate({borderTopColor:"#F7D600", borderBottomColor:"#F7D600", borderLeftColor:"#F7D600", borderRightColor:"#F7D600"}, "fast", '', function()
      {
         $j('#basket').animate({borderTopColor:"#fff", borderBottomColor:"#fff", borderLeftColor:"#fff", borderRightColor:"#fff"}, "fast");
      }
   );
}

function flashBasketAndData(data)
{
   $j('#basket').animate({borderTopColor:"#F7D600", borderBottomColor:"#F7D600", borderLeftColor:"#F7D600", borderRightColor:"#F7D600"}, "fast", '', function()
      {
         $j('#basket-container').html(data);
         $j('#basket').animate({borderTopColor:"#fff", borderBottomColor:"#fff", borderLeftColor:"#fff", borderRightColor:"#fff"}, "fast");
      }
   );
}

function openFlashCardPicker()
{
   GB_showCenter("Select your flash cards", ROOT_URL + "flashcard-box.php",700,1000);
}

function editFC(packlink)
{
    ref = $j(packlink).parent().parent().parent().find('input').attr('name');
    GB_showCenter("View/Edit Flash card pack "+ref, ROOT_URL + "flashcard-box.php?packid="+ref,700,1000);
}

function openFoodCardPicker()
{
   GB_showCenter("Select your food cards", ROOT_URL + "foodcard-box.php",700,1000);
}

function editFDC(packlink)
{
    ref = $j(packlink).parent().parent().parent().find('input').attr('name');
    GB_showCenter("View/Edit Food card pack "+ref, ROOT_URL + "foodcard-box.php?packid="+ref,700,1000);
}


