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 descOpen=null;

//var ratingSet=new Array();

var prevSel=0;

function pageLoad()
{
    l2lcookies=new CookieJar({expires:3600, path: '/'});
    //var re=/#(\d+)/;
    var re=/[?](\d+)/;
    var a=re.exec(window.location);
 //   alert(a);
    if (a)
    {
        for (i=0;i<imgCnt;i++)
        {
            if (ids[i]==a[1])
            {
                curSel=i;
                skipLicenses=i;
                break;
            }
        }
    }

    initCarousel();
    descOpen=false;

    $('prevBtn').observe('click', goPrev);
    $('nextBtn').observe('click', goNext);
    //$('likeItBtn').observe('click', setRating);

    new Dialog.Box('updatingDialog');
    new Dialog.Box('errorDialog');
    //new Dialog.Box('post_comment_dlg');
    //new Dialog.Box('post_comment_success_dlg');
    //new Dialog.Box('post_comment_error_dlg');
    //new Dialog.Box('post_comment_validation_error_dlg');

}

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++;
    }

    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 draw()
{
    updateProductData();

    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.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: {scope:'carousel'}});

    return;
}

function updateProductData()
{

    var curSel=picList[2];
    var i=$('img_'+curSel).readAttribute('rel');

    currentId=ids[i];
    currentGlobalNo=i;

    $('licenseno').update((curSel%productCount)+1);

    $$('.productId')[0].value=currentId;
    $$('.productId')[1].value=currentId;

    $('prodName').update(names[i]);
    $('prodDesc').update(descriptions[i]);
    //$('price_value').update(prices[i]);
    //$('addtocart_form_product').value=ids[i];


    var urlFacebook = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent("http://license2live.com/#" + currentId);
    $$('.shareFacebook')[0].setAttribute("onclick", "location.href=\""+urlFacebook+"\"");
    $$('.shareFacebook')[1].setAttribute("onclick", "location.href=\""+urlFacebook+"\"");

    var urlTwitter = "http://twitter.com/home?status=" + encodeURIComponent("Check out this this License to Live at http://license2live.com/#" + currentId);
    $$('.shareTwitter')[0].setAttribute("onclick", "location.href=\""+urlTwitter+"\"");
    $$('.shareTwitter')[1].setAttribute("onclick", "location.href=\""+urlTwitter+"\"");

    //$$('.sendLicense .description a')[0].href="sendlicense/card/index/id/"+currentId+"/";
    //$$('.sendLicense .description a')[1].href="sendlicense/card/index/id/"+currentId+"/";

    var urlSendEcard = "sendcard/card/index/id/"+currentId+"/";
    $$('.sendEcard')[0].setAttribute("onclick", "location.href=\""+urlSendEcard+"\"");
    $$('.sendEcard')[1].setAttribute("onclick", "location.href=\""+urlSendEcard+"\"");
    
    //update meta tags
    
    // First, get the array of meta-tag elements
    var metatags = document.getElementsByTagName("meta");

    // Iterate through the array, and update the title, url, type and image values

    var cnt;
    for (cnt = 0; cnt < metatags.length; cnt++)

    {
        var name = metatags[cnt].getAttribute("name");
        var content = metatags[cnt].getAttribute("content");

        // Update the title meta tag
        if (name == "fbtitle")
              metatags[cnt].setAttribute("content", names[i]);
        if (name == "fburl")
              metatags[cnt].setAttribute("content", encodeURIComponent("http://staging.license2live.com/?" + currentId));
        if (name == "fbtype")
              metatags[cnt].setAttribute("content", "product");
        if (name == "fbimage")
              metatags[cnt].setAttribute("content", document.getElementById('img_'+curSel).getAttribute("src"));
        if (name == "fbdescr")
              metatags[cnt].setAttribute("content", descriptions[i]);              
    };

/* old fb like code
    $('likeItBtn').update('<iframe id="likeItBtn" src="http://www.facebook.com/plugins/like.php?href=' + encodeURIComponent("http://license2live.com/?" + currentId) + '&amp;layout=button_count&amp;show_faces=false&amp;action=like&amp;font=trebuchet+ms&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:80px"></iframe>');


        $('likeItBtn').update('<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="' + encodeURIComponent("http://staging.license2live.com/?" + currentId) + '" show_faces="false" width="450" font="trebuchet ms"></fb:like>');
        
        FB.XFBML.parse(document.getElementById('likeItBtn'));
        

*/        

    

    //$$('#post_comment_dlg .title')[0].update(names[i]);


    //$('likeit_count').update(likeItsCount[i]);
//    $$('.comment_count')[0].update(reviewCount[i]);
//    $$('.comment_count')[1].update(reviewCount[i]);

/* removing references to review in order to prepare for FB comments
    if (reviewCount[i]==0)
    {
        $('andcomments').hide();
        $('prodComments').hide();
        $$('#postComment .msg')[0].update("Be the first to post a comment");
    }
    else
    {
        $('andcomments').show();
        $('prodComments').show();
        $$('#postComment .msg')[0].update("Post your own comment");
    }
*/
    /**
    alert(customerRatings[i]);
    new Effect.Morph('rating_gauge', {
        style: "width: " + customerRatings[i]+"%"
    });

    **/

    //fillComments(i);
}

function fillComments(prodNo)
{
    var html='';
    for (var i=0;i<reviews[prodNo].length;i++)
    {
        html+="<span class='reviewTitle'>"+reviews[prodNo][i].title+"</span><span class='reviewNickname'> by "+reviews[prodNo][i].nickname+"</span>";
        html+="<div class='reviewText'>"+reviews[prodNo][i].detail+"</div>";

    }
    $('prodCommentsBody').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 filterProducts(event,tagId)
{

    Event.stop(event);

    var html='';
    imgCnt=0;
    currentTag='All occasions';
    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;

    curSel=0;

    $('carousel').update(html);
    initCarousel();
}

function submitComment()
{
    $$('#errorDialog .msg')[0].update("So sorry, but we cannot submit your comment at this time.  Please try again later.");
    $('errorDialog').hide();
    $$('#updatingDialog .msg')[0].update("Saving your review...");
    $('updatingDialog').show();

    new Ajax.Request($('commentForm').action+"id/"+currentId, {
        method: 'post',
        parameters: $('commentForm').serialize(),
        onSuccess: function(transport) {
            $('updatingDialog').hide();
            openPostDialogConfirm();
        },
        onException: function(req,ex)
        {
            $('updatingDialog').hide();
            $('errorDialog').show();
        },
        onFailure: function()
        {
            $('updatingDialog').hide();
            $('errorDialog').show();
        }

    });
}

function updateContent(transport)
{
    try
    {
        response = eval('(' + transport.responseText + ')');
    }
    catch (e)
    {
        response = {};
    }

    if (response.update_sections)
    {
        for (var i=0;i<response.update_sections.length;i++)
        {
            var section=response.update_sections[i];
            var elements=$$(section.classname);

            if (elements && elements.length>0)  elements[0].replace(section.html);
        }
    }
}


function imageClicked(event)
{
    Event.stop(event);

    var x=Event.pointerX(event);
    var off=$('carousel').viewportOffset();
    x-=off.left;

    if (x>657&&x<916)
    {
        goNext();
    }
    else if (x>0&&x<255)
    {
        goPrev();
    }
    else //if (ids[target.readAttribute('rel')]*1==currentId)
    {
        toggleProductDetails(event);
        //openFullDialog("");
    }


}

function toggleProductDetails(event)
{
  Event.stop(event);
/*
  if (descOpen)
  {
    new Effect.Fade('prodDetails');
    descOpen=false;
  }
  else
  {
    $('prodDetails').show();
    new Effect.Fade('prodDetails',{duration: 1,from: 0, to: 1 });
  Effect.ScrollTo('carousel',{duration: 0.5, transition:Effect.Transitions.Expo.easeOut});
    descOpen=true;
  }
  */
  jQuery('#prodDetails a').click();
  
  if (jQuery('#prodDetails h3.ui-state-active').length>0)
  {  
    Effect.ScrollTo('carousel',{duration: 0.5, transition:Effect.Transitions.Expo.easeOut});
  }
  return false;
} 
/////////

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();
}

