var curSel=0;
var carouselInterval=null;
var currentId=0;
var currentGlobalNo=0;
var globalPos=0;
var picList;
var productCount;
var skipLicenses=20;
var l2lcookies=null;

var ratingSet=new Array();

var prevSel=0;

function pageLoad()
{
  l2lcookies=new CookieJar({expires:3600, path: '/'});
  var re=/#(\d+)/;
  var a=re.exec(window.location);
  if (a)
  {
  for (i=0;i<imgCnt;i++)
  {
    if (ids[i]==a[1])
    {
      curSel=i;
      skipLicenses=i;
      break;
    }
  }
  } 
  
  
  initCarousel();
  startCarousel();

  $('comments_body').hide();
    $('comments_link_indicator').update('(+)');
  commentsOpen=false;

  if (a)  stopCarousel();

  $('prev_btn').observe('click',onGoPrev);

  $('next_btn').observe('click',onGoNext);
 
  $('play_btn').observe('click',startCarousel);
  $('pause_btn').observe('click',stopCarousel);
  
  $('comments_link_link').observe('click',toggleComments);

  $$('.rating-box')[0].observe('click',setRating);
  
  $$('.rating-box')[0].observe('mousemove',ratingMouseOver);
  $$('.rating-box')[0].observe('mouseleave',ratingMouseOut);
  
  $$('#sendecard a')[0].observe('click',stopCarousel);
  
  new Dialog.Box('post_comment_dlg');
  new Dialog.Box('post_comment_success_dlg');
  new Dialog.Box('post_comment_error_dlg');
  new Dialog.Box('post_rating_success_dlg');
  new Dialog.Box('post_rating_error_dlg');
  new Dialog.Box('post_comment_validation_error_dlg');

//  new Dialog.Box('circledlg');
  new Dialog.Box('wait_dlg');
/*
  if (!a && l2lcookies.get('circle_dont_show')==null)
  {
  $('circledlg').show();
  }
*/
}

function initCarousel()
{                                         
 picList=new Array();
 
 for (i=0;i<imgCnt;i++)
 {
  picList.push(i);
 }

 var i=imgCnt; 
 var html='';
 while (imgCnt<6)
 {
  var el=$$('#carousel img')[imgCnt%productCount];
  
  html+='<img id="img_'+imgCnt+'" rel="'+$(el).readAttribute('rel')+'" class="img" src="'+el.src+'" alt="'+el.title+'" title="'+el.title+'" />';
  picList.push(imgCnt);
  imgCnt++;
 }
 //var car=$('carousel');
 if ($('carousel') && $('carousel').innerHTML) html=$('carousel').innerHTML+html;
 $('carousel').update(html);
 
 picList.unshift(picList.pop());
 picList.unshift(picList.pop()); 
 
 $$('#carousel img').invoke('observe','click',imageClicked);

 $('licenseno').update(curSel+1);
 updateProductData();
 $('licensecount').update(productCount);
 
  if (skipLicenses>0)
  {
   for (i=0;i<skipLicenses;i++)
   {
  picList.push(picList.shift());
  prevSel=curSel;
  globalPos++;
  curSel++;
   }
   skipLicenses=0;
  }
  draw();
  
}

function translatePos(pos)
{
  return pos%imgCnt;
}

function draw()
{
 updateProductData();

 //alert(picList);
 
 var effectQueue=new Array();
 for (i=0;i<imgCnt;i++)
 {
  var y=28;
  
  var x=-310;

  var morph=false;
  if (i>=0 && i<5) morph=true;

  var w=260;
  if (i==2)
  { 
    w=375;
    y=0;
  }
  

  var h=125;
  if (i==2) h=180;
  
  var scale=70;
  if (i==2) scale=100;
  
  if (i==1) x=0;
  if (i==2) x=270;
  if (i==3) x=655;
  
  if (i>=4)
    x=935;
  
  if (i==0 && prevSel>curSel) morph=false;
  if (i==4 && prevSel<curSel) morph=false;
  
  if (morph)
  {
    /*effectQueue.push(new Effect.Morph('img_'+picList[i],{style:'height: '+h+'px; width: '+w+'px; left:'+x+"px; top: "+y+"px;",
        duration: 1,
        transition:Effect.Transitions.Expo.easeOut,sync:true  }));
        */
        
    effectQueue.push(new Effect.Move('img_'+picList[i],{x: x,y:y,mode:'absolute',sync: true,transition:Effect.Transitions.Expo.easeOut}));
    if (i==2)
    {
      effectQueue.push(new Effect.Scale('img_'+picList[i],144,{scaleMode: { originalHeight: 125, originalWidth: 260 },duration: 1,sync:true,transition:Effect.Transitions.Expo.easeOut}));
    }
    else
    {
      effectQueue.push(new Effect.Scale('img_'+picList[i],scale,{scaleMode: { originalHeight: 180, originalWidth: 375 },duration: 1,sync:true,transition:Effect.Transitions.Expo.easeOut}));
    }
    
    
    if (i==2)
      effectQueue.push(new Effect.Fade('img_'+picList[i],{duration: 1, from: 0.5, to: 1,transition:Effect.Transitions.Expo.easeOut,sync:true}));
    else
      effectQueue.push(new Effect.Fade('img_'+picList[i],{duration: 1, to: 0.5,transition:Effect.Transitions.Expo.easeOut,sync:true}));
      
  }
  else
  {
    $('img_'+picList[i]).setStyle({left: x+"px", top: y+"px",width: w+"px",height: h+"px"});
    $('img_'+picList[i]).setStyle({left: x+"px", top: y+"px",width: w+"px",height: h+"px",opacity: 0.5});
  }
 }
 //new Effect.Parallel(effectQueue,{queue: {position:'end',scope: 'carousel'}});
 new Effect.Parallel(effectQueue);
 
 return;

}

function updateProductData()
{
 
 var curSel=picList[2];
 var i=$('img_'+curSel).readAttribute('rel');

 currentId=ids[i];
 currentGlobalNo=i;

 $('licenseno').update((curSel%productCount)+1);
 
 $('prod_description').update(descriptions[i]); 
 $('addtocart_form_product').value=ids[i];
 $('price_value').update(prices[i]);
 $$('#post_comment_dlg .title')[0].update(names[i]);
 
 $$('#sendecard a')[0].href="/sendcard/card/index/id/"+currentId+"/";
 
 $$('.qty')[0].value='1';
 
 $('comment_count').update(reviewCount[i]);
 
 if (reviewCount[i]==0)
 {
  $('andcomments').hide();
 }
 else
 {
  $('andcomments').show();
 }
 
 new Effect.Morph('rating_gauge',{style: "width: "+ratings[i]+"%"});
 
 showTags(i);
 fillComments(i);
 
 if (typeof(ratingSet[currentGlobalNo])!='undefined')
 {
  $$('.rating-box')[0].setStyle('cursor: auto;');
 }
 else
 {
  $$('.rating-box')[0].setStyle('cursor: pointer;');
 }
}

function fillComments(prodNo)
{
  var html='';
  for (var i=0;i<reviews[prodNo].length;i++)
  {
    html+="<div class='review-title'><a href='/review/product/view/id/"+reviews[prodNo][i].id+"/'>"+reviews[prodNo][i].title+"</a> <span class='review-nick'>by "+reviews[prodNo][i].nickname+"</span></div>";
    html+="<div class='review-text'>"+reviews[prodNo][i].detail+"</div>";
    
  }
  $('comments_list').update(html);
  
}

function goprev()
{
 picList.unshift(picList.pop());
 prevSel=curSel;
 globalPos--;
 curSel--;
 draw();
}

function gonext()
{
 picList.push(picList.shift());
 prevSel=curSel;
 globalPos++;
 curSel++;
 draw();

}

function onGoNext()
{
 stopCarousel();
 gonext();
}

function onGoPrev()
{
 stopCarousel();
 goprev();
}

function toggleCarousel()
{
  if (carouselInterval==null)
    startCarousel();
  else
    stopCarousel();
}
function startCarousel()
{
  //if (carouselInterval==null) gonext();
  
  carouselInterval=window.setInterval(gonext,8000);
  $('play_btn').hide();
  $('pause_btn').show();
}

function stopCarousel()
{
  if (carouselInterval!=null) 
  {
  window.clearInterval(carouselInterval);
  carouselInterval=null;
  $('play_btn').show();
  $('pause_btn').hide();
  }
}

var commentsOpen=false;
function toggleComments(event)
{
  Event.stop(event);
  stopCarousel();
  if (commentsOpen)
  {
    new Effect.Fade('comments_body');
      $('comments_link_indicator').update('(+)');
    commentsOpen=false;
  }
  else
  {
    $('comments_body').show();
    new Effect.Fade('comments_body',{duration: 1,from: 0, to: 1 });
    $('comments_link_indicator').update('-');
  Effect.ScrollTo('carousel',{duration: 0.5, transition:Effect.Transitions.Expo.easeOut});
    commentsOpen=true;
  }
  return false;
}
function closePopup()
{
  $('circledlg').hide();
  
  if ($('dont_show_circle').checked)
  {
  l2lcookies.put('circle_dont_show',1);
  }
  
  return false;
}

function showTags(cnt)
{
 var html='';
 for(i=0;i<tags[cnt].length;i++)
 {
  html+="<a href='#' onClick='return filterProducts(event,"+tags[cnt][i].id+");'>"+tags[cnt][i].name+"</a>";
  if (i<tags[cnt].length-1) html+=', ';
 }
 $('tag_list').update(html);
}

function filterProducts(event,tagId)
{
 Event.stop(event);
 stopCarousel();
 //alert(taggedProducts[tagId]);
 
 var html='';
 imgCnt=0;
 currentTag='All licenses';
 for(i=0;i<image.length;i++)
 {
  var skip=true;

  for (k=0;k<tags[i].length;k++)
  {
    if (tags[i][k].id==tagId)
    {
      currentTag=tags[i][k].name;
      break;
    }
  }
  
  if (tagId>0)
  {
    for (k=0;k<taggedProducts[tagId].length;k++)
    {
      if (taggedProducts[tagId][k]==ids[i])
      {
        skip=false;
        break;
      }
    }
  }
  
  if (!skip || tagId==0)
  {
    html+='<img id="img_'+(imgCnt)+'" rel="'+i+'" class="img" src="'+image[i].src+'" alt="'+image[i].title+'" title="'+image[i].title+'" />';
    imgCnt++;
  }
  
 }

 productCount=imgCnt;
 /*while (imgCnt<6)
 {
  picList.push(imgCnt%productCount);
  html+='<img id="img_'+imgCnt+'" rel="'+i%productCount+'" class="img" src="'+image[i%productCount].src+'" alt="'+image[i%productCount].title+'" title="'+image[i%productCount].title+'" />';
  imgCnt++;
 }
 */
 
 $('current_tag').update(currentTag + ' Licenses');
 if (tagId==0)
 {
  $('tag').hide();
 }
 else
 {
  $('tag').show();
 }
 
 curSel=0;
 $('carousel').update(html);
 initCarousel();
}

function postCommentDlg()
{
 stopCarousel();
 $('post_comment_dlg').show();
 return false;
}

function submitComment()
{
 if($$('#post_comment_dlg input[name=nickname]')[0].value.replace(/^\s+/, '').replace(/\s+$/, '')==''
 ||$$('#post_comment_dlg input[name=title]')[0].value.replace(/^\s+/, '').replace(/\s+$/, '')==''
 ||$$('#post_comment_dlg textarea[name=detail]')[0].value.replace(/^\s+/, '').replace(/\s+$/, '')=='')
  {
    alert('Please fill out all fields');
    return;
  }
 
 $('wait_dlg').show();

 new Ajax.Request($('review_form').action+"id/"+currentId, {
  method: 'post',
  parameters: $('review_form').serialize(),
  onSuccess: function(transport) {
   $('wait_dlg').hide();
   $('post_comment_dlg').hide();
   $('post_comment_success_dlg').show();
  },
  onException: function(req,ex)
  {
   $('wait_dlg').hide();
   $('post_comment_error_dlg').show();
  },
  onFailure: function()
  {
   $('wait_dlg').hide();
   $('post_comment_error_dlg').show();
  }

  });

}

function setRating(event)
{
 if (typeof(ratingSet[currentGlobalNo])!='undefined') return;
  
 stopCarousel();
 
 var off=$(event.target).viewportOffset();

 var rating=Math.ceil((event.clientX-off.left)/30);
 ratings[currentGlobalNo]=rating*20;
 $('wait_dlg').show();
 

 new Ajax.Request("/ajaxreview/product/postrating/id/"+currentId, {
  method: 'post',
  parameters: "rating="+rating,
  onSuccess: function(transport) {
   $('wait_dlg').hide();
   $('post_comment_dlg').hide();
   $('post_rating_success_dlg').show();
   ratingSet[currentGlobalNo]=true;
   
   $$('.rating-box')[0].setStyle('cursor: auto;');
  },
  onException: function(req,ex)
  {
   $('wait_dlg').hide();
   $('post_rating_error_dlg').show();
  },
  onFailure: function()
  {
   $('wait_dlg').hide();
   $('post_rating_error_dlg').show();
  }

  });
}

function ratingMouseOver(event)
{
  if (typeof(ratingSet[currentGlobalNo])!='undefined') return;
  
  var off=$(event.target).viewportOffset();
  var x=Math.ceil((event.clientX-off.left)/29)*29;
  $('rating_gauge').setStyle("width:"+x+"px");
  
}

function ratingMouseOut()
{
 var curSel=picList[2];
 var i=$('img_'+curSel).readAttribute('rel');
 $('rating_gauge').setStyle("width:"+ratings[i]+"%");
}


function imageClicked(event)
{
 Event.stop(event);

 var x=Event.pointerX(event);
 var off=$('carousel').viewportOffset();
 x-=off.left;
 //alert(x);
 if  (x>657&&x<916) 
 {
  stopCarousel();  
  gonext();
 } 
 else if  (x>0&&x<255)
 { 
    stopCarousel();
  goprev();
 }
 else //if (ids[target.readAttribute('rel')]*1==currentId)
 {
  toggleComments(event);
 }
 
 
}
/////////

Object.extend(Effect.Transitions, (function() {

    //----------------------------------------------------------------------
    // Function transformations
    //----------------------------------------------------------------------

    // easeIn to easeOut and vice versa
    function reverse(eq, t)
    {
        return 1 - eq(1 - t);
    }

    // easeIn to easeInOut
    function easeInToEaseInOut(easeIn, t)
    {
        t = 2 * t;
        return 0.5 * (t < 1 ? easeIn(t) : 2 - easeIn(2 - t));
    }

    // easeOut to easeInOut
    function easeOutToEaseInOut(easeOut, t)
    {
        t = 2 * t;
        return 0.5 * (t < 1 ? 1 - easeOut(1 - t) : 1 + easeOut(t - 1));
    }

    // easeIn / easeOut pair to easeInOut
    function easeInOutPairToEaseInOut(easeIn, easeOut, t)
    {
        t = 2 * t;
        return 0.5 * (t < 1 ? easeIn(t) : 1 + easeOut(t - 1));
    }

    //----------------------------------------------------------------------
    // Function set builders
    //----------------------------------------------------------------------

    // Build a function set from a complete set of easing functions
    function functionSet(easeIn, easeOut, easeInOut)
    {
        return {
            easeIn   : easeIn,
            easeOut  : easeOut,
            easeInOut: easeInOut
        };
    }

    // Build a complete function set from just an easeIn
    function functionSetFromEaseIn(easeIn)
    {
        return {
            easeIn   : easeIn,
            easeOut  : reverse.curry(easeIn),
            easeInOut: easeInToEaseInOut.curry(easeIn)
        };
    }

    // Build a complete function set from just an easeOut
    function functionSetFromEaseOut(easeOut)
    {
        return {
            easeIn   : reverse.curry(easeOut),
            easeOut  : easeOut,
            easeInOut: easeOutToEaseInOut.curry(easeOut)
        };
    }

    // Build a complete function set from an easeIn / easeOut pair
    function functionSetFromEaseInOutPair(easeIn, easeOut)
    {
        return {
            easeIn   : easeIn,
            easeOut  : easeOut,
            easeInOut: easeInOutPairToEaseInOut.curry(easeIn, easeOut)
        };
    }

    // Build a complete function set from just an easeIn,
    // where the given function has custom parameters
    function customizableFunctionSetFromEaseIn()
    {
        var args = $A(arguments);
        var easeIn = args.shift();

        function customEaseIn()
        {
            var args = [0].concat($A(arguments));

            return function(t)
            {
                args[0] = t;
                return easeIn.apply(this, args);
            };
        }

        function customEaseOut()
        {
            return reverse.curry(customEaseIn.apply(this, arguments));
        }

        function customEaseInOut()
        {
            return easeInToEaseInOut.curry(customEaseIn.apply(this, arguments));
        }

        var myEaseIn = customEaseIn.apply(this, args);
        myEaseIn.custom = customEaseIn;
        var myEaseOut = reverse.curry(myEaseIn);
        myEaseOut.custom = customEaseOut;
        var myEaseInOut = easeInToEaseInOut.curry(myEaseIn);
        myEaseInOut.custom = customEaseInOut;

        return {
            easeIn   : myEaseIn,
            easeOut  : myEaseOut,
            easeInOut: myEaseInOut
        };
    }

    //----------------------------------------------------------------------
    // Useful pre-computed values
    //----------------------------------------------------------------------

    var HALF_PI = Math.PI / 2;
    var TWO_PI  = 2 * Math.PI;

    //----------------------------------------------------------------------
    // Penner's tween equations, simplified for Scriptaculous
    //----------------------------------------------------------------------

    function Quad_easeIn(t)
    {
        return t * t;
    }

    function Cubic_easeIn(t)
    {
        return t * t * t;
    }

    function Quart_easeIn(t)
    {
        return t * t * t * t;
    }

    function Quint_easeIn(t)
    {
        return t * t * t * t * t;
    }

    // This one is not Penner's: it's just a generalized case, for use when
    // i.e. Quad is too "soft" for your tastes but Cubic is too "quick"
    // (in this specific case you could use Pow.custom(2.5) for example)
    function Pow_easeIn(t, p)
    {
        return Math.pow(t, p);
    }

    function Back_easeIn(t, s)
    {
        return t * t * ((s + 1) * t - s);
    }

    // TODO (maybe): customize (customizableize? :-) ) this one
    function Bounce_easeOut(t)
    {
        if (t < (1 / 2.75))
            return 7.5625 * t * t;
        if (t < (2 / 2.75))
            return 7.5625 * (t-= (1.5 / 2.75)) * t + 0.75;
        if (t < (2.5 / 2.75))
            return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
        return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
    }

    function Circ_easeIn(t)
    {
        return -1 * (Math.sqrt(1 - t * t) - 1);
    }

    function Circ_easeOut(t)
    {
        t -= 1;
        return Math.sqrt(1 - t * t);
    }

    function Elastic_easeIn(t, a, p)
    {
        if (t == 0) return 0;
        if (t == 1) return 1;
        if (a < 1)
        {
            a = 1;
            var s = p / 4;
        }
        else
        {
            var s = p / TWO_PI * Math.asin(1 / a);
        }
        return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TWO_PI / p));
    }

    function Expo_easeIn(t)
    {
        return (t == 0) ? 0 : Math.pow(2, 10 * (t - 1));
    }

    function Expo_easeOut(t)
    {
        return (t == 1) ? 1 : 1 - Math.pow(2, -10 * t);
    }

    function Sine_easeIn(t)
    {
        return Math.cos(t * HALF_PI) + 1;
    }

    function Sine_easeOut(t)
    {
        return Math.sin(t * HALF_PI);
    }

    function Sine_easeInOut(t)
    {
        return -0.5 * (Math.cos(Math.PI * t) - 1);
    }

    //--------------------------------------------------------------------------
    // Build and return the equation sets
    //--------------------------------------------------------------------------

    return {
        Quad   : functionSetFromEaseIn(Quad_easeIn),
        Cubic  : functionSetFromEaseIn(Cubic_easeIn),
        Quart  : functionSetFromEaseIn(Quart_easeIn),
        Quint  : functionSetFromEaseIn(Quint_easeIn),
        Pow    : customizableFunctionSetFromEaseIn(Pow_easeIn, 2), // Defaults to Quad
        Back   : customizableFunctionSetFromEaseIn(Back_easeIn, 1.70158),
        Bounce : functionSetFromEaseOut(Bounce_easeOut),
        Circ   : functionSetFromEaseInOutPair(Circ_easeIn, Circ_easeOut),
        Elastic: customizableFunctionSetFromEaseIn(Elastic_easeIn, 1, 0.3),
        Expo   : functionSetFromEaseInOutPair(Expo_easeIn, Expo_easeOut),
        Sine   : functionSet(Sine_easeIn, Sine_easeOut, Sine_easeInOut)
    };

})());

ImagesObserver = Class.create({
  initialize: function(el, options) {
    this.options = {
      onImagesLoaded: Prototype.emptyFunction
    };
    Object.extend(this.options, options || { });
    
    this.el = $(document.body);
    if (typeof el != 'undefined') this.el = $(el);
      
    this.pe = new PeriodicalExecuter(this._checkImagesState.bind(this), (1/10));
  },
  
  _checkImagesState: function() {
    if (this._areImagesLoaded(this.el)) {
      this.pe.stop();
      if (this.options.onImagesLoaded != Prototype.emptyFunction)
        this.options.onImagesLoaded(this.el);
      else
        document.fire('images:loaded', { el: this.el });
    }
  },
  
  _areImagesLoaded: function(el) {
    return el.select('img').all(function(img) {

      return (img.readyState == 'complete' || img.complete ||
        !(typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0));
    });
  }
});
// EOF
//document.observe('dom:loaded', pageLoad);
//Event.observe(window,'load', pageLoad);
if (IS_IE6)
{
 Event.observe(window,'load', pageLoad);//window.setTimeout(pageLoad,1000)
}
else
{
 document.observe('images:loaded', pageLoad);
 new ImagesObserver();
}
