/*********************Nicolas**********************/

/******indexOf fo Ie**************/
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}


/*******************cookies Manager*********************/

function getCookie(sName) {
    var oRegex = new RegExp("(?:; )?" + sName + "=([^;]*);?");

    if (oRegex.test(document.cookie)) {
        return unescape(RegExp["$1"]);
    } else {
        return null;
    }

}

function setCookie (sName, value, min) {
    var expires;
    if (min) {
        var date = new Date();
        date.setTime(date.getTime()+(min*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = sName+"="+escape(value)+expires+"; path=/";
}

function eraseCookie(sName) {
    setCookie(sName,"",-1);
    return null;
}

//Système onglet
function customCarrousel () { }

// définition des valeurs par défaut
customCarrousel.prototype.target = '#carrousel';
customCarrousel.prototype.urlParam = 'tab';
customCarrousel.prototype.autoSlide = true;
customCarrousel.prototype.crossTransition = true;
customCarrousel.prototype.autoHeight = false;
customCarrousel.prototype.autoWidth = false;
customCarrousel.prototype.timeToSlide = 3000;
customCarrousel.prototype.slideSpeed = 500;
customCarrousel.prototype.stopAfterFirstClick = false;
customCarrousel.prototype.htmlTemplate = '<tbody><tr><td class="leftColumn"><zone/></td><td class="rightColumn"><list/></td></tr></tbody>';
customCarrousel.prototype.order = ['tab', 'zone'];
customCarrousel.prototype.tabContainer = 'ul';
customCarrousel.prototype.tabLister = 'li';
customCarrousel.prototype.zIndex = 10;
customCarrousel.prototype.carrousel = function () {

    if (!$(this.target).length) return;
    var tags =[],
    zone=[],
    x=0,
    y=0,
    i=1,
    me=this;
  

    $(this.target).css({
        'position':'relative'
    });

    // récupération des élemetns du webBlock
    $(this.target+ ' > tbody > tr').each(function () {
        var thisElement = $(' > td', this);

        var thisTag = thisElement.eq(me.order.indexOf("tab")).html(),
            thisZone = thisElement.eq(me.order.indexOf("zone"));

        if (me.autoWidth) x = Math.max (thisZone.width(), x);
        if (me.autoHeight) y = Math.max (thisZone.height(), y);

        tags.push('<'+me.tabLister+' class="tagListElements" ><a class="tagLinks tagLink'+i+'">'+thisTag + '</a></'+me.tabLister+'>');
        var tempZone = thisZone.wrapInner('<div class="tagsZone tagZone'+i+'" />'),
            tempZoneChild = tempZone.children().detach();
        zone.push(tempZoneChild);
        i++;
    });

    // Position initiale diaporama
    var numberOfItems = tags.length,
    timeOut,
    uriCourant = document.location.href,
    reg= new RegExp ("[&\\?]"+this.urlParam+"=(\\d+)", "g"),
    infosInUrl = reg.exec(uriCourant);

    var current = null,
    next = (infosInUrl && infosInUrl.length>0 && parseInt(infosInUrl[1])>0 && parseInt(infosInUrl[1])<=numberOfItems )? parseInt(infosInUrl[1]) : 1;

    //création HTML
    $(this.target).html(this.htmlTemplate);

    $(this.target+' zone:first').replaceWith('<div class="tagsListZone" style="position:relative;"></div>');
    $(this.target+' list:first').replaceWith('<'+this.tabContainer+' class="tagsList">'+tags.join('')+'</'+this.tabContainer+'>');
    for (var j=0; j<numberOfItems; j++) {
        $(me.target+' .tagsListZone:first').append(zone[j]);
    }

    var  zones = $(this.target+' .tagsListZone:first .tagsZone');
    
    zones.css({'opacity':0});
    
    zones.css({
        'left':0,
        'top':0,
        'position':'absolute'
    })
    .hide();

    if (this.autoHeight) $(this.target+' .tagsListZone:first .tagsZone').height(y);
    if (this.autoWidth) $(this.target+' .tagsListZone:first .tagsZone').width(x);


    shadeIt (1);
    // fonction de transition fondu/enchainé :
    function shadeIt (speed) {

        if (current==next) return;
        if(current) {
            var currentZone = $(me.target+' .tagsListZone:first > .tagZone'+current);

            if (me.crossTransition) {
                currentZone.css({
                    'position':'absolute'
                });
            }

           currentZone.animate({
                    'opacity': 0,
                    'z-index':0
                }, {
                    duration : speed,
                    complete : function () {
                        $(this)
                        .css({
                        'position':'absolute'
                        })
                        .hide();
                        if (!me.crossTransition) showNext ();
                    }
                });
            

            $(me.target+' .tagsList:first > .tagListElements > .tagLink'+current).removeClass('taghighlighted');
        }

        $(me.target+' .tagsList:first > .tagListElements > .tagLink'+next).addClass('taghighlighted');

        if (me.crossTransition || !current ) showNext ();

        function showNext () {
            var toMove = $(me.target+' .tagsListZone:first > .tagZone'+next);
            
            toMove.show();
            toMove.css({
                'z-index':1,
                'position':'relative'
            });
  
                toMove.animate({
                    'opacity': 1,
                    'z-index':me.zIndex
                }, {duration : speed,
                     complete : function () {
                                    if (this.style.removeAttribute) this.style.removeAttribute('filter');
                                }
                });
        }
        current=next;
    }

    // affichage zone correspondante lors du clic sur un élement du carousel
    $(this.target).delegate('.tagsList:first .tagLinks','click', function(){
        var meAgain = $(this).attr('class'),
        reg = new RegExp ('tagLink(\\d+)', 'g');
        next = parseInt(reg.exec(meAgain)[1], 10);

        if (me.autoSlide) {
            clearTimeout (timeOut);
        }
        if (me.autoSlide && !me.stopAfterFirstClick)  {
            autoscroll();
        }
        shadeIt (me.slideSpeed);
    });

    //auto défilement
    function autoscroll () {
        timeOut = setTimeout (function () {
            next = (next<numberOfItems) ? next+1 : 1;
            shadeIt (me.slideSpeed);
            autoscroll();
        }, me.timeToSlide);
    }

    if (this.autoSlide) autoscroll ();
}


/****************************FICHE PRODUIT*****************************/
// déplacement table option.
function moveOptionTbl (target, optionrow, optioncol) {
    if (!target) return;

    var optionTbl = $('.PBOptLstTable'),
        optionZoneTarget = $(target),
        rowIndex=0,
        colIndex=0;

    if (!optionTbl.length || !optionZoneTarget.length ) return;

        optionTbl.find('tr').each(function () {
            $(this)
            .addClass(optionrow + rowIndex)
            .find('td').each(function () {
               $(this).addClass(optioncol + colIndex);
               colIndex++;
            });
         rowIndex++;
         colIndex=0;
        });
    
        optionTbl.find('.btnoptdetail').remove();
        optionZoneTarget.eq(0).replaceWith(optionTbl.eq(0).detach());
        
}

// Onglets fiche produit
function makeTabs (target) {
    if (!$(target).length) return;

    var myTabs = new customCarrousel ();
    myTabs.target = target;
    myTabs.autoSlide = false;
    myTabs.crossTransition = false;
    myTabs.htmlTemplate = '<tbody><tr><td><list/></td></tr><tr><td><zone/></td></tr></tbody>';
    myTabs.carrousel(); 
}

// Suppresion du bouton acheter, et titre d'origine. 
function manageItemContent(target) {
    $('img.imgmain, .imgcontainer').remove();
    if (!$('.PBOptLstTable').length)  {
        $('buybutton').eq(0).replaceWith($('.btnaddtocart').eq(0).detach());
    }
    $('.sectiondataarea table tr').eq(0).remove();
    $(target).replaceWith(OxPdtName.replace('&#92;', ''));
}

// Fonction simplifiée PikaChoose
function carrouselLauncher() {}
carrouselLauncher.prototype.target='#carrouselImages';
carrouselLauncher.prototype.height=200;
carrouselLauncher.prototype.width=350;
carrouselLauncher.prototype.margin=8;
carrouselLauncher.prototype.carrousel=true
carrouselLauncher.prototype.containerId='productDiaporama';
carrouselLauncher.prototype.execute = function () {
    $(this.target).wrapInner('<ul id="' + this.containerId + '" class="jcarousel-skin-pika"></ul>');
    $(this.target + ' img').each(function(){
        var texteAlt = $(this).attr('title');
        $(this).wrap('<li></li>');
        if (texteAlt != undefined)  $(this).after('<span>' + texteAlt + '</span>');
    });
    $('head').append('<style type="text/css"> ' + this.target + ' .pika-stage{height:' + this.height + 'px; }'
    + this.target + ' .pika-stage, ' + this.target + ' .pika-textnav { width: ' + this.width + 'px; } </style>');
        $('#' + this.containerId).PikaChoose({carousel:this.carrousel});
}

// Fonction simplifiée prettyPhoto
function lightboxIt (target) {
     var j, k;
        $('a[class*='+target+']')
        .each(function() {
            j = $('img', this).attr('title');
            k = $(this).text();
            j = (j == undefined )? k : j;
            $(this).attr('title', j)
        })
        .prettyPhoto({
			animation_speed: 'fast', /* fast/slow/normal */
			autoplay_slideshow: false, /* true/false */
			opacity: 0.80, /* Value between 0 and 1 */
			show_title: false,
			default_width: 500,
			default_height: 344,
			keyboard_shortcuts: true
	});
   
}

// rajout des réseaux sociaux.
function addSocialNetwork (target) {
    var zone = $(target);
    if (!zone.length) return;
   var facebookHTML = '<div class="addthis_toolbox addthis_default_style">'
                     + '&nbsp;<a class="addthis_button_facebook" addthis:url="http://www.oxatis.com'+OxPdtUrl+'" addthis:title="+'+OxPdtName+'" Title="Partager avec Facebook" ><img src="/Files/13825/boutique-img/icon/icon-fb.png"/></a>'
                     + '&nbsp;<a class="addthis_button_twitter" addthis:url="http://www.oxatis.com'+OxPdtUrl+'" addthis:title="'+OxPdtName+'" title="Partager avec Twitter"><img src="/Files/13825/boutique-img/icon/icon-twitter.png"/></a>'
                     + '&nbsp;<g:plusone></g:plusone>'
                     + '</div>';
    zone.replaceWith(facebookHTML);
    
    var po = document.createElement('script');
    po.type = 'text/javascript';
    po.src = 'http://s7.addthis.com/js/250/addthis_widget.js';
    var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(po, s);


}

// mini bloc "témoignage" avec affichage aléatoire d'un temoignage
function addTestimonial (target) {
    if (!$('#' + target).length || !$(target).length) return;

    var testimonials = $('#' + target+ ' > tbody > tr > td'),
        nb = testimonials.length,
        rand_no = Math.random(),
        myElement = Math.ceil(rand_no * nb) - 1;

     $(target).eq(0).replaceWith(testimonials.eq(myElement).html());

}

//Mise en forme des upsales
 function upSalesManager (source) {
    var relatedPdts = $(source);
    if (!relatedPdts.length) return;

    $('td', relatedPdts).css('border', 'none');

    $(' .PBLayoutTable', relatedPdts).each(function () {
        var thisElement = $('td', this),
            thisImage = thisElement.eq(0).find('img').attr('src'),
            thisBgImage = (typeof(thisImage) != 'undefined')? 'url(' + thisImage + ')' : 'none',
            indexEq = (typeof(thisImage) != 'undefined')? 1 : 0,
            thisURL = thisElement.eq(indexEq).find('a').attr('href'),
            htmlData = '<div class="upSaleImg" ><a class="relatedLink" href="' + thisURL +
                       '" style="background-image:'+thisBgImage+'"><span class="relatedMoreInfos"></span></a></div>' +
                       '<div class="upSaleTitle" >' + thisElement.eq(indexEq).html() + '</div>';

         $(this).replaceWith('<div class="PBLayoutTable">'+htmlData+'</div>');
    });

     $('.PBLayoutTable').css('textAlign', 'center');
 }


// Mise en forme des crossSales
 function crossSalesManager (source, target) {
    var relatedPdts = $(source);
    if (!relatedPdts.length) return;

    $('td', relatedPdts).css('border', 'none');

    $(' .PBLayoutTable', relatedPdts).each(function () {
        var thisElement = $('td', this),
            thisImage = thisElement.eq(1).find('img').attr('src'),
            thisBgImage = (typeof(thisImage)!='undefined')? 'url(' + thisImage + ')' : 'none',
            indexEq = (typeof(thisImage) != 'undefined')? 2 : 1,
            thisURL = thisElement.eq(indexEq).find('a').attr('href'),
            htmlData = '<div class="crossSaleImg" ><a class="relatedLink" href="' + thisURL +
                       '" style="background-image:'+thisBgImage+'"><span class="relatedMoreInfos"></span></a></div>' +
                       '<div class="crossSaleTitle" >' + thisElement.eq(indexEq).html() + '</div>';

                   
         $(this).replaceWith('<div class="PBLayoutTable">'+htmlData+'</div>');

    });

    var htmlContent = relatedPdts.detach();
    $(target).replaceWith(htmlContent);
 }


//Conversion Prix
function convertToPrice (price, coef, decimal) {

    if (!decimal) decimal=',';
    var amount = parseFloat(price)/coef;
    amount = amount.toString();
    amount =  (decimal==',')?  amount.replace('.', ',') : amount;

    var expregTest=new RegExp(decimal+'\\d\\d',"g"),
    expregTest2=new RegExp(decimal,"g"),
    test = amount.match(expregTest),
    test2 = amount.match(expregTest2);

    if  (!test && test2) {
        amount += '0';
    }

    return amount;
}

// Affichage des prix HT
function showTTC (setting) {
    
    if (!setting.target) setting.target='.optionTableCol1';
    if (!setting.newPriceType) setting.newPriceType='TTC';
    if (!setting.devise) setting.devise='EUR';
    if (!setting.className) setting.className='TTCValue';
    if (!setting.decimalType) setting.decimalType=',';
    if (!setting.vatRate) setting.vatRate=1.196;

    var prices = $(setting.target);

    prices.each( function () {

                var htmlTarget=$(this);

            // récupération prix
                function getPrice (tempClass) {
                var localTarget = htmlTarget.find(tempClass);
                if (!localTarget.length) return null;
                var answer=localTarget.html(),
                    expreg=new RegExp('([\\d,\\.]+)(\\s|\\&nbsp;)+'+setting.devise,"gi"),
                    tempValue = expreg.exec(answer);
                    return (tempValue && tempValue.length>0)? tempValue[1] : null;
                }

                 var price = getPrice ('.PBShortTxt');

            // Affichage des prix recalculés.
            if (price) {
                var tempNumber = (setting.decimalType!=',')? price.replace(',', '') : price.replace('.', '').replace(',', '.'),
                    otherPrice = Math.round(tempNumber*parseFloat(setting.vatRate)*100);

                otherPrice = convertToPrice (otherPrice, 100, setting.decimalType);

                var HTValue='<div class="'+setting.className+'">'+otherPrice+' ' + setting.devise+' ' + setting.newPriceType+"</div>";

                 $(this).append(HTValue);
            }

         });

    $('.' + setting.className).hide();
    $('.PBOptLstTable').delegate(setting.target, "hover", function(){
	$(this).find('.' + setting.className).fadeToggle("fast", "linear");
    });
}



/****************popup WB*************************/

 function addLinksToWb (target, WbId, returnId, prodirect) {
     if (!returnId) returnId=false;
     if (!prodirect) prodirect=false;
     var testButtonArea= $(target);
     if (!testButtonArea.length) return;
     testButtonArea.attr ('href','javascript:openPopupWb('+WbId+', ' + returnId + ', false, ' + prodirect + ');');
 }

 function openPopupWb (WbId, returnId, returnMode, prodirect) {
 
     var wbContainer;
         if (!returnMode) wbContainer = addPopupStructure ();
         else wbContainer= $('#WBMainData');

    $.ajax({
        url:'wsGetWebBlock.asp?WBID='+WbId,
        dataType:'json',
        success: function(Data) {
            importTemplate (Data);
        }
    });

    function importTemplate (data) {

        if (!data || data.error) {
            return;
        }

        var htmlModel = replaceFromTemplate (data.htmlContent, 'http:\\/\\/#RETURN#', 'javascript:returnToSite(\'#WBInfoZone\');');
            htmlModel = replaceFromTemplate (htmlModel, 'http:\\/\\/#CALLBACK#', 'javascript:sendCallbackForm('+WbId+', ' + returnId + ', ' + prodirect + ');');
        wbContainer.html(htmlModel);
        if (returnMode) window.setTimeout(function() {returnToSite('#WBInfoZone');}, 5000);
    }
 }

 function addPopupStructure () {
    var testWbArea= $('#WBInfoZone');

    if (testWbArea.length<1) {
        $('body').eq(0).prepend('<div id="WBInfoZone"><div id="WBInfobody"></div><div id="WBInfocontainer"><div id="WBMainArea"><div id="WbCloseButton"><a href="javascript:returnToSite(\'#WBInfoZone\');" class="closeButtonAction">[Cerrar]</a></div><div id="WBMainData"></div></div></div></div>');
    }
    $('#WBInfobody')
        .css('height',$(document).height())
        .bind ('click', function() {
            returnToSite('#WBInfoZone');
        });

    var WbAreacontainer=$('#WBMainData');
    $('#WBInfoZone').show();

    WbAreacontainer.append('<div id="shopcartpreload"></div>');
    $('#WBInfocontainer').css('top',$(window).scrollTop());

    return WbAreacontainer;
}


//soumission du WB formulaire en ajax
function sendCallbackForm (wbId, returnId, prodirect) {

    // ajout d'une balise form
    var thisForm = $("#WBFormPopup");

    if (!thisForm.length) {
        $("#WBMainData").wrapAll('<form id="WBFormPopup"/>');
        thisForm = $("#WBFormPopup");
    }

    // vérification des champs obligatoires
    var thisFormTester = thisForm.serializeArray(),
        key;

    for (key in thisFormTester) {
        if (thisFormTester[key].value == "") {
            var currentlInput = $('*[name="'+thisFormTester[key].name+'"]');
            if (currentlInput.attr("wbvalreq")==1) {
               alert (currentlInput.attr("wbvalmsg"));
               return;
            }
        }
    }

    //envoi du formulaire
    postCallbackForm ();

    function postCallbackForm () {
        var postComplement,
            subMenuTitle = $('#menu-v10-submenu .menu_items_title'),
            subMenuSelected = $('#menu-v10-submenu a.selected'),
            title = $('title');

       /* Rajout de d'infos sur la page courrante du visiteur */
       //nom du service
        if (typeof(OxPdtName) != 'undefined' && OxPdtName) {
            postComplement = '&WBF100-PAGE=SERVICE : ' + escape(unescape(OxPdtName.replace('&#92;', '')));
            launchPost (postComplement);
            return;
        }

        //ou titre du sous menu
        if (subMenuTitle.length && subMenuSelected.length) {
            postComplement = '&WBF100-PAGE=' + escape(unescape(subMenuTitle.eq(0).html() + ':' + subMenuSelected.eq(0).html()));
            launchPost (postComplement);
            return;
        }

        //ou nom du webblock
        if (typeof(OxCompName) != 'undefined' && OxCompName=='WebBlock' && typeof(OxPageName ) != 'undefined' && OxPageName ) {
            postComplement = '&WBF100-PAGE=WEBLOCK : ' + escape(unescape(OxPageName.replace('&#92;', '')));
            launchPost (postComplement);
            return;
        }

        // ou html title
        if (title.length ) {
            postComplement = '&WBF100-PAGE=PAGE : ' + escape(unescape(title.eq(0).html()));
            launchPost (postComplement);
            return;
        }

        //ou rien, mais on aura cherché quand mÃªme...
        launchPost (postComplement);
    }

    function launchPost (postComplement) {
        
        //rajout des infos de tracking
        var moreInfos = trackVisitors(),
            now = new Date(),
            elapsedTime = Math.ceil(now.getTime()/1000) - moreInfos.date,
            addProdirect = "",
            since = Math.floor(elapsedTime / 60) + " minutes";

        postComplement += "&WBF101PAGES-VUES=" + moreInfos.pages + "&WBF102TEMPS-PASSE=" + escape(since);
        
        if (prodirect) addProdirect = "&OxParam=WBFProDiProspect";
        
        //envoi du formulaire
        $.post("PBCPPlayer.asp?PFORM=1&PW=1&ID=" + wbId, thisForm.serialize() + '&ActionID=0' + addProdirect + postComplement, function(data) {
             showReturnCallback (data, wbId, returnId );
           });
     }

    // affichage du retour ou d'un WB
    function showReturnCallback (data, wbId, returnId) {

       if (!returnId) {
           var htmlModel = cleanHtmlTags (data);
           htmlModel = replaceFromTemplate (htmlModel, 'http:\\/\\/#RETURN#', 'javascript:returnToSite(\'#WBInfoZone\');');
           $('#WBInfocontainer').html(htmlModel);
       } else {
           openPopupWb (returnId, null, true);
       }
   }
}

//désactivation touche "entrée" des formulaires
function NoEnterKey() {
var keycode = 0 ;
if (window.event) keycode = window.event.keyCode;
//NS? else if (event) keycode = event.which;
if (keycode == 13) return false ;
return true ;
}

//Tracking Visites
function trackVisitors (mode) {
    var travelValue, result ={};
    travelValue = getCookie('travelValue');

    if (!travelValue) {
        var d = new Date();
        travelValue = 'date=' + Math.ceil(d.getTime()/1000) + '&pages=0';
    }

    var getpages=new RegExp("pages=(\\d*)","g"),
        detdate=new RegExp("date=(\\d*)","g");
    result.date = parseInt(detdate.exec(travelValue)[1]),
    result.pages = parseInt(getpages.exec(travelValue)[1]) + 1;

    if (mode=='set') {
        travelValue = 'date=' + result.date + '&pages=' + result.pages;
        setCookie('travelValue',travelValue, 60);
    }

    return result;
}
/***************************************Panier dynbamique V2.2**************************************/

//Ajax scheduler
function webServiceQuery(){
}
webServiceQuery.prototype.url = '/wsGetCategories.asp?Mode=3&shopcart=1';
webServiceQuery.prototype.dataType = 'json';
webServiceQuery.prototype.answer = null;
webServiceQuery.prototype.addParams = null
webServiceQuery.prototype.handleResponse = function(data) {
    if (this.fonction) this.fonction(data, this.addParams);
}
webServiceQuery.prototype.handleError = function() {
    if (this.fonctionError) this.fonctionError();
}

function Json (webService) {
    this.webService=webService;
}
Json.prototype.onFinish = function (fn)
{
    this.onFinishCallBack=fn;
}
Json.prototype.ajaxSend = function () {
    var me=this;
    $.ajaxSetup({
        'beforeSend' : function(xhr) {
            xhr.overrideMimeType('text/html; charset=iso-8859-1');
        }
    });

    $.ajax({
        url: this.webService.url,
        cache: true,
        dataType: this.webService.dataType,
        success: function(Data) {
            me.webService.handleResponse (Data);
            me.webService.answer = Data;
            if (me.onFinishCallBack) me.onFinishCallBack();
        },
        error:function (xhr, ajaxOptions, thrownError){
            if (window.console) console.log ("error", xhr.status, thrownError);
            me.webService.handleError ();
        }
    });
}

function startQuery(toSend){
    this.toSend = toSend;
    this.count=0;
}

startQuery.prototype.process = function(){
    var me = this;
    for (var i=0; i<this.toSend.length; i++) {
        this.toSend[i].onFinish(function(){
            me.returnProcess();
        });
        this.toSend[i].ajaxSend();
    }
}

startQuery.prototype.returnProcess = function(){
    this.count++;
    if ( this.toDo && (this.count == this.toSend.length) ) this.toDo();
}

startQuery.prototype.onDone = function(toDo){
    this.toDo = toDo;
}



//Panier dynamique
function addHTMLStructure () {
    var testCartArea= $('#shopcartreturn');

    if (testCartArea.length<1) {
        $('body').eq(0).prepend('<div id="shopcartreturn"><div id="shopcartbody"></div><div id="shopcartcontainer"></div></div>');
    }
    $('#shopcartbody')
        .css('height',$(document).height())
        .bind ('click', function() {
            returnToSite('#shopcartreturn');
        });

    var shopcartcontainer=$('#shopcartcontainer');
    $('#shopcartreturn').show();

    shopcartcontainer.append('<div id="shopcartpreload"></div>').css('top',$(window).scrollTop());

    return shopcartcontainer;
}


function dynamicCart () {}
dynamicCart.prototype.smallCartTmpl="";
dynamicCart.prototype.returnCartTmpl="";
dynamicCart.prototype.cookieSaving=true;
dynamicCart.prototype.cartTemplateCookie=null;
dynamicCart.prototype.ajaxCartSubmiter=  function (nProductID, strURLParams) {
   var me=this,
       shopcartcontainer = addHTMLStructure (),
       multiAjax = [];

    // Panier dynamqiue
    var getCart = new webServiceQuery();
    getCart.url = 'PBShoppingCart.asp?AjaxMode=1&'+strURLParams;
    var firstQuery = new Json(getCart);
    multiAjax.push(firstQuery);

    // recup tmpl
    var getTmpl = new webServiceQuery();
    getTmpl.url = 'wsGetWebBlock.asp?WBID='+this.returnCartTmpl;
    var secondQuery = new Json(getTmpl);
    multiAjax.push(secondQuery);

    // exécution simultanée des 2 requetes
    var doQuery = new startQuery(multiAjax);
    doQuery.onDone(showCart);
    doQuery.process();

    function showCart () {

        if (!getCart.answer || !getTmpl.answer || getTmpl.error)  return;

        var htmlModel=getTmpl.answer.htmlContent,
        itemsCount=getCart.answer.result,
        totalItemsCount=getCart.answer.cartqtytotal,
        totalAmount=convertToPrice(getCart.answer.cartsubtotalnet, 100);


        me.setDynamicCart ();
        htmlModel = replaceFromTemplate (htmlModel, '#ADDEDITEMS#', itemsCount, true );
        htmlModel = replaceFromTemplate (htmlModel, '#TOTALITEMS#', totalItemsCount, true );
        htmlModel = replaceFromTemplate (htmlModel, '#CARTAMOUNT#', totalAmount);
        htmlModel = replaceFromTemplate (htmlModel, 'http:\\/\\/#RETURN#', 'javascript:returnToSite(\'#shopcartreturn\');');
        shopcartcontainer.html(htmlModel);
    }

}

// affichage du mini-panier
dynamicCart.prototype.setDynamicCart = function () {


    if (this.cookieSaving) {
        this.cartTemplateCookie = getCookie('cartTemplateCookie');
    }
    var me=this;
    if (!this.cartTemplateCookie) {
        $.ajax({
            url: 'wsGetWebBlock.asp?WBID='+this.smallCartTmpl,
            cache: true,
            dataType:'json',
            success: function(data) {
                me.cartTemplateCookie = data.htmlContent ;
                me.setCartCookie ();
            }
        });
    } else {
        this.showCartInDocument ();
    }

}

dynamicCart.prototype.setCartCookie = function  () {
    if (!this.cartTemplateCookie) return;
    if (this.cookieSaving) {
        setCookie ('cartTemplateCookie', this.cartTemplateCookie);
    }
    this.showCartInDocument ();
}

dynamicCart.prototype.showCartInDocument = function () {

    var btncontainer = $('#showCartContainer');
    if (!btncontainer.length) return;

    var reg=new RegExp("QTYTotal=(\\d*)","g"),
    regAmount=new RegExp("SubTotalNet=(\\d*)","g"),
    chaine=getCookie('PCart'),
    nbItems=reg.exec(chaine),
    amount=regAmount.exec(chaine),
    totalCart = (amount && amount.length>1 && amount[1]!="")? convertToPrice(amount[1], 100) : 0,
    items = (nbItems && nbItems.length>=1 && nbItems[1]!="")?  parseInt(nbItems[1]) : 0;

    var cartModel = this.cartTemplateCookie;
    cartModel = replaceFromTemplate (cartModel, '#NBITEMS#', items , true );
    cartModel = replaceFromTemplate (cartModel, '#CARTAMOUNT#', totalCart);

    btncontainer.html(cartModel);
   

}

// bouton continuer
function returnToSite(target) {
    $(target).hide();
}

/******************gestionnaire de template*************************/
function replaceFromTemplate (htmlModel, tag, value, recursive) {
    var reg = {};

    if (recursive) {

        reg = {
            expression:new RegExp(tag+"\\s*\\{\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\s*\\[([^\\}|\\]]*)\\]\\}", "g"),
            tagValue:new RegExp("#value#", "g")
        }

        var doResult=reg.expression.exec(htmlModel);
        if (!doResult) return null;
        var idValue = (value>2)? 3 : value+1;
        var newHTML=doResult[idValue].replace(reg.tagValue, value);
        htmlModel=htmlModel.replace(reg.expression,newHTML);

    } else {

        reg = {
            tagValue:new RegExp(tag, "g")
        }
        htmlModel=htmlModel.replace(reg.tagValue,value);
    }

    return htmlModel;
}

/************************Recupération ID catégorie****************************/
function getCatId () {
    var currentCatId=getCookie('currentCatId');

    if (!OxCatID1 && !OxCatID2 && !OxCatID3) {
        eraseCookie('currentCatId');
        return null;
    }

    if (!currentCatId) {
        if (OxCatID1) {
            setCookie ('currentCatId', OxCatID1);
            return OxCatID1;
        }
        if (OxCatID2) {
            setCookie ('currentCatId', OxCatID2);
            return OxCatID2;
        }
        if (OxCatID3) {
            setCookie ('currentCatId', OxCatID3);
            return OxCatID3;
        }
    } else {
        switch (parseInt(currentCatId, 10)) {
            case parseInt(OxCatID1, 10):
                setCookie ('currentCatId', OxCatID1);
                return OxCatID1;
                break;
            case parseInt(OxCatID2, 10):
                setCookie ('currentCatId', OxCatID2);
                return OxCatID2;
                break;
            case parseInt(OxCatID3, 10):
                setCookie ('currentCatId', OxCatID3);
                return OxCatID3;
                break;
            default:
                if (OxCatID1) {
                    setCookie ('currentCatId', OxCatID1);
                    return OxCatID1;
                }
                if (OxCatID2) {
                    setCookie ('currentCatId', OxCatID2);
                    return OxCatID2;
                }
                if (OxCatID3) {
                    setCookie ('currentCatId', OxCatID3);
                    return OxCatID3;
                }
                break;
        }
    }
}

/****************Mise en forme des sous-catégories*****************/
function replaceSubCat () {

    var catID = getCatId (),
        catList = [],
        template = '<li class="subCatElement"><a href="#linkurl#"><img src="#imgfilename#"/></a></li>';

    if (!catID) return;
    $.getJSON('wsGetCategories.asp?CatID='+catID+'&Mode=3&shopcart=1&sort=position&sortdir=1', function(data) {
        secondCheck (data);
    });

    function secondCheck (data) {
        if ($('.sectionsubcatlist').length) {
            replaceZone (data);
            return;
        }
        if (parseInt(data.categorypath.levelcount)>1) {
            var newCatID = data.categorypath.hierarchy[data.categorypath.levelcount-2];
            $.getJSON('wsGetCategories.asp?CatID='+newCatID+'&Mode=3&shopcart=1&sort=position&sortdir=1', function(data) {
                replaceZone (data);
            });
        }
    }
    
    function replaceZone (data) {
        if (!data.categories) return;
        $.each(data.categories, function(key, val) {
            var httmlTemplate = template.replace('#imgfilename#', val.imgfilename);
            httmlTemplate = httmlTemplate.replace('#linkurl#', val.url);
            catList.push(httmlTemplate);
        });

        $('.sectionsubcatlist').eq(0).remove();

        $('<ul/>', {
                id:'subCatContainer',
                html: catList.join('')
            }).appendTo('.sectiontbarea:first');

    }
}

/*mise en surbrillance du menuH actif*/
function activeMenu () { }

activeMenu.prototype.target= "#maincontainer";
activeMenu.prototype.attribute= "class";
activeMenu.prototype.prefix= ".menu-";
activeMenu.prototype.activeClass= "active";
activeMenu.prototype.detection= "active";
activeMenu.prototype.subTarget= "a:first";
activeMenu.prototype.detectionParam= "class";
activeMenu.prototype.debug= false;
activeMenu.prototype.focus= function () {

    if (!$(this.target).length) return;
    
    var classname = $(this.target).attr(this.attribute),
        classList = classname.split(" "),
        key,
        localClass;

    for (key in classList) {
        if (classList.hasOwnProperty(key)){
            localClass = this.prefix + classList[key];
            if (window.console && this.debug) console.log (localClass);
            $(localClass+ ' ' + this.subTarget).addClass(this.activeClass);
        }
    }

    if (!$(this.detection).length || !$(this.detection).attr(this.detectionParam) ) return;

    localClass = this.prefix + $(this.detection).attr(this.detectionParam);
    if (window.console && this.debug) console.log (localClass);
    $(localClass+ ' ' + this.subTarget).addClass(this.activeClass);

}

/**Mise en forme de la page mon compte**/
function orderFormBuilder (texts) {
    if (!$('.scorderform, .useraccount').length) return;
    var defaultTexts = {
        accountID : 'N&deg; de compte Client',
        CEIAccount : 'N&deg; Centre d\'expertise',
        accountMsg :"Le num\351ro de votre compte client doit \352tre une suite de chiffres.\r\n\r\n Reportez-vous au menu [Comte > Propri\351t\351s du Titulaire] de l'administration de votre site pour le connaitre.",
        CEIMsg : "Le num\351ro du centre d\'expertise doit \352tre une suite de chiffres."
    }
    
    var opts = $.extend(defaultTexts, texts);
    
    //Saisie des valeurs par dÃ©faut et masquage des zones
    var adress = $('input[name="BillingAddress3"]');
    adress.val('.');
    var adressContainer = adress.closest('table').closest('td');
    adressContainer.hide();
    adressContainer.next().hide();

    $('input[name="BillingState"]').closest('tr').hide();
    $('#DISPSHIPADDR').closest('table').hide();
    $('#SubscribeToNews').closest('table').hide();
    $('input[name="BillingCity"]').closest('td').appendTo( $('input[name="BillingZipCode"]').closest('tr'));
    $('input[name="BillingCountryItem"]').closest('td').attr('colspan', '2');

    var Company = $('input[name="Company"]');
    Company.closest('tr').hide();

    //Vérification si le champ  "société" a été activé
    if (!Company.length) return;

    //récupération des valeurs des deux champs
    var recupID = Company.val(),
        regSite=new RegExp("ID-Site:(\\d*)","g"),
        nbSite=regSite.exec(recupID),
        regCEI=new RegExp("ID-CEI:(\\d*)","g"),
        nbCEI=regCEI.exec(recupID),
        site = (nbSite && nbSite.length>1 && nbSite[1]!="")? nbSite[1] : '',
        CEI = (nbCEI && nbCEI.length>1 && nbCEI[1]!="")? nbCEI[1] : '';

    //ajout des nouvelles cellules
    var htmlContent = '<table cellspacing="0" cellpadding="3" border="0">'
                    + '<tbody><tr>'
                    + '<td valign="bottom">'
                    + '<span class="PBStatic PBNotReq">' + opts.accountID + '</span><br>'
                    + '<input id="IDSite" type="TEXT" value="'+site+'" maxlength="30" style="width: 114px" size="30" name="IDSite" class="PB">'
                    + '</td><td valign="bottom">'
                    + '<span class="PBStatic PBNotReq">' + opts.CEIAccount + '</span><br>'
                    + '<input id="IDCEI" type="TEXT" value="'+CEI+'" maxlength="30" style="width: 114px" size="30" name="IDCEI" class="PB">'
                    + '</td>'
                    + '</tr></tbody>'
                    + '</table>';

    $('input[name="EmailAddress"]').closest('table').after(htmlContent);

    //mise Ã  jour du champ sociÃ©tÃ© en fonction du contenu des cellules
    $('#IDSite , #IDCEI, #NameCEI').change(function () {
        var IDSite = $('#IDSite').val();
        var IDCEI = $('#IDCEI').val();

        if (IDSite && IDSite != parseInt(IDSite)) {
            alert (opts.accountMsg);
            $('#IDSite').val('');
            IDSite = null;
        }

        if (IDCEI && IDCEI != parseInt(IDCEI)) {
            alert (opts.CEIMsg);
            $('#IDCEI').val('');
            IDCEI = null;
        }

        var result = (IDSite)? 'ID-Site:' + IDSite : '';
        result += (IDSite && IDCEI)? ' - ' : '';
        result += (IDCEI)? 'ID-CEI:' + IDCEI : '';

        Company.val (result);
    });
}

function setupOrderForm (target) {
    var zoneCtrl = $(target);
    if (!zoneCtrl.length) return;
    var zoneToMove = zoneCtrl.closest('table').closest('tr').closest('table');

    zoneToMove.find('table').each (function () {
        var cellToMove = $('tr > td', this);
        cellToMove.attr('valign', 'center');
        cellToMove.eq(1).before(cellToMove.eq(2));
    });
}


/**********************SEB****************************/

function vMenuRenderer(){

    var speedmenu = 250;
    var PdtID = $('input[name="HVParentID"]').val();
    var _open	= true ;

    //On Wrap le Menu
    $("#vmenu ul.submenu").wrap('<div class="submenu_container_global"><div class="submenu_container"></div></div>');

    //Pour chaque Submenu, on supprime les attribut OnmouseOut, OnMouseOver et Href
    $("#vmenu ul.submenu").each(function(){
        myclasse1 = $(this).parent().parent().parent().parent().attr('id') ;
        $("#"+myclasse1+" a.menu:first").removeAttr('href') ;
        $("#"+myclasse1+" div div div ul.submenu").removeAttr('onmouseout')  ;
        $("#"+myclasse1+" div div div ul.submenu").removeAttr('onmouseover') ;
        $("#"+myclasse1).removeAttr('onmouseout')  ;
        $("#"+myclasse1).removeAttr('onmouseover') ;

        //Si la classe de l'élément correspond au PdtID, on ouvre le parent et on ajoute la classe selected
        if( $("#"+myclasse1+" div div div ul.submenu li").hasClass('pdID-'+PdtID) ){
            $("#"+myclasse1+" div div div ul.submenu li.pdID-"+PdtID+" a.menu").addClass("selected");

            menu_open(myclasse1,true);
            myclasse = myclasse1;
        }
    }
    )

    //On affiche notre Vmenu une fois le Wrap terminÃ©
    $("ul#vmenu").css("visibility", "visible");
    $("ul#vmenu li ul.submenu").css("visibility", "visible");

    //lorsque qu'on clique sur un Vmenu li
    $("#vmenu").delegate("#vmenu li", 'click', function(){

            if(_open){
                //On Stock le menu courant dans une variable
                myclasse = $(this).attr('id');
                if(! myclasse == ''){
                    menu_open(myclasse,false);
                }
            }
            else{
                myclasse2 = $(this).attr('id') ;
                if(! myclasse2 == ''){
                    //Si c'est le même menu, on ferme tous les menus
                    if( (myclasse2 == myclasse) && (_open == false) ){
                        menu_close(myclasse,false);
                    }
                    //Sinon on ferme tous les menus et on ouvre le Menu
                    else{
                        myclasse = $(this).attr('id');
                        menu_open(myclasse2,false);
                    }
                }
            }
        }
        )

    function menu_open(myclasse,flag){

        _open = false;
        //On retire la class Open des différents menu
        $("#vmenu li").removeClass("open");
        $("#"+myclasse).addClass("open");

        //On récupère la taille de notre Submenu et on rajoute 1 pour harmoniser
        _h =  $("#"+myclasse+" .submenu_container_global .submenu_container .submenu").height() + 1;

        if(!flag){
            //On affiche notre SubMenu
            $("#vmenu li .submenu_container_global").animate({
                height:0
            } , speedmenu );
            $("#"+myclasse+" .submenu_container_global").animate({
                height : _h
            } , speedmenu);
        }
        else{
            $("#vmenu li .submenu_container_global").css("height", 0 );
            $("#vmenu #"+myclasse+" .submenu_container_global").css("height", _h );
        }
    }

    function menu_close(myclasse){
        _open = true;
        //On ferme tous les SubMenus et on retire la classe open des LI
        $("#vmenu li .submenu_container_global").animate({
            height :0
        } , speedmenu);
        $("#vmenu li .submenu_container_global").animate({
            height :0
        } , speedmenu);
        $("#vmenu li").removeClass("open");
    }

}

//Ouverture du XML ( passé en variable ) pour charger les autres catégories
function open_xml() {

    if ($('.sccatalog').length || !$('#maincontainer').length ) return;

    $.ajax( {
        type: "GET",
        url: "/Files/13825/ES-menu-v10.xml",
        dataType: "xml",
        success: function(xml) {
            //Pour chaque Noeud Cat
            $(xml).find('cat').each(
                function()
                {
                    //On récupère les différentes ID de la page et du XML
                    var id = $(this).attr('idwebblock').replace('webblock wbid','');
                    var cat = $(this).attr('cat');
                    var current = $("#maincontainer").attr('class').replace('webblock wbid','') ;

                    //Si l'id current est dans la liste
                    if( id.match(current) ){

                        if(!isNaN(current))	{
                            $('#menu-v10').wrapInner('<div id="menu-v10-submenu"><ul></ul></div>');
                            //On boucle sur la catégorie du current
                            $(xml).find('cat').each(
                                function()
                                {
                                    //On récupère les différentes variables de chaque ligne
                                    var id = $(this).attr('idwebblock').replace('webblock wbid','');
                                    var title = $(this).attr('title');
                                    var url = $(this).attr('url');

                                    //Si on est dans la catégorie
                                    if( cat == $(this).attr('cat')  ){

                                        //Si c'est un titre...
                                        if( id == 'title'){
                                            $('<li class="menu_items_title"></li>').html( title ).appendTo('#menu-v10-submenu ul');
                                        }
                                        //Sinon
                                        else{
                                            if( (current == id) && (title != '') ){
                                                $('<li class="menu_items"></li>').html('<a class="selected" href="' + url + '">' + title + '</a><br>').appendTo('#menu-v10-submenu ul');
                                            }
                                            else{
                                                if ( title != '' ){
                                                    $('<li class="menu_items"></li>').html('<a href="' + url + '">' + title + '</a><br>').appendTo('#menu-v10-submenu ul');
                                                }
                                            }
                                    }
                                }
                            });
                    }
                    else {
                        $("#bodycolumn2").prepend('<div id="bodycolumn-xml"><div id="menu-v10-submenu"><ul></ul></div></div>');
                        $(xml).find('cat').each(
                            function()
                            {

                                //On récupère les différentes variables de chaque ligne
                                var id = $(this).attr('idwebblock').replace('webblock wbid','');
                                var title = $(this).attr('title');
                                var url = $(this).attr('url');

                                //Si on est dans la catégorie
                                if( cat == $(this).attr('cat')  ){

                                    //Si c'est un titre...
                                    if( id == 'title'){
                                        $('<li class="menu_items_title"></li>').html( title ).appendTo('#menu-v10-submenu ul');
                                    }
                                    //Sinon
                                    else{
                                        if( (current == id) && (title != '') ){
                                            $('<li class="menu_items"></li>').html('<a class="selected" href="' + url + '">' + title + '</a>').appendTo('#menu-v10-submenu ul');
                                        }
                                        else{
                                            if ( title != '' ){
                                                $('<li class="menu_items"></li>').html('<a href="' + url + '">' + title + '</a>').appendTo('#menu-v10-submenu ul');
                                            }
                                        }
                                }
                            }
                        });
                }
            }
        });
    }
});
}

/*Social Bar*/

function socialbar(){

	$("#social-js").appendTo("body");
	$("#social-js").css("display","block");
	
	var flagsocial = true;
	
	$(".social-close").click(function (){
		if(flagsocial){$("#social-js").animate({left: 0}, 200, function(){flagsocial=false});}
		else $("#social-js").animate({left : -140}, 200, function(){flagsocial=true});
		}
	)	
	if(!$.browser.msie) {
		$(".social-icon").animate({opacity:0.7},200);
		$(".social-icon").mouseover(function(){$(this).animate({opacity:1},200);})
		$(".social-icon").mouseout(function(){$(this).animate({opacity:0.7},200);})
	}
}


/*vérification formulaires */

function VerifForm (){

    var VerifMail = ControlChamp(document.getElementById('email'),'email');
    var VerifFirstname = ControlChamp(document.getElementById('firstname'),'firstname');
    var VerifLastname = ControlChamp(document.getElementById('lastname'),'lastname');
    var VerifPhone = ControlChamp(document.getElementById('phone'),'phone');

    if ((!VerifMail) ||(!VerifFirstname) ||(!VerifLastname)||(!VerifPhone)  ) {

        var msg = "Vous n\'avez pas rempli correctement le formulaire. Veuillez v\351rifier ";

        if(!VerifMail) {
            msg = msg +"votre Mail ";
        }
        if(!VerifFirstname) {
            msg = msg + "votre Pr\351nom ";
        }
        if(!VerifLastname) {
            msg = msg + "votre Nom ";
        }
        if(!VerifPhone) {
            msg = msg + "votre T\351l\351phone ";
        }

        alert (msg);

    }

    else {
        document.AbonnementDOLIST.submit();
    }
}

function VerifForm2 (){

    var VerifMail = ControlChamp(document.getElementById('email2'),'email');
    var VerifFirstname = ControlChamp(document.getElementById('firstname2'),'firstname');
    var VerifLastname = ControlChamp(document.getElementById('lastname2'),'lastname');
    var VerifPhone = ControlChamp(document.getElementById('phone2'),'phone');

    if ((!VerifMail) ||(!VerifFirstname) ||(!VerifLastname)||(!VerifPhone)  ) {

 
        var msg = "Vous n\'avez pas rempli correctement le formulaire. Veuillez v\351rifier ";
        if(!VerifMail) {
            msg = msg +"votre Mail ";
        }
        if(!VerifFirstname) {
            msg = msg + "votre Pr\351nom ";
        }
        if(!VerifLastname) {
            msg = msg + "votre Nom ";
        }
        if(!VerifPhone) {
            msg = msg + "votre T\351l\351phone ";
        }
        alert (msg);
    }

    else {
        document.AbonnementDOLIST2.submit();
    }

}

 

function ControlChamp(obj,typ){
var Regex;
    switch (typ){
        case 'email':
            Regex = new RegExp('^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$', 'gi');
            break;
        case 'date':
            Regex = new RegExp('^(([1-9]|0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9][0-9]|[0-9][0-9][0-9][0-9]))?$', 'gi');
            break;
        case 'lastname':
            Regex = new RegExp('^[^ ].*$', 'gi');
            break;
        case 'firstname':
            Regex = new RegExp('^[^ ].*$', 'gi');
            break;
        case 'phone':
            Regex = new RegExp('[-\\. +\\d]+', 'gi');
            break;
    }

    var Result = Regex.test(obj.value);
    return Result;

}

/********************Ressources externes*****************************/


/*
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function(g){
    var q={
        vertical:!1,
        rtl:!1,
        start:1,
        offset:1,
        size:null,
        scroll:3,
        visible:null,
        animation:"normal",
        easing:"swing",
        auto:0,
        wrap:null,
        initCallback:null,
        setupCallback:null,
        reloadCallback:null,
        itemLoadCallback:null,
        itemFirstInCallback:null,
        itemFirstOutCallback:null,
        itemLastInCallback:null,
        itemLastOutCallback:null,
        itemVisibleInCallback:null,
        itemVisibleOutCallback:null,
        animationStepCallback:null,
        buttonNextHTML:"<div></div>",
        buttonPrevHTML:"<div></div>",
        buttonNextEvent:"click",
        buttonPrevEvent:"click",
        buttonNextCallback:null,
        buttonPrevCallback:null,
        itemFallbackDimension:null
    },m=!1;
    g(window).bind("load.jcarousel",function(){
        m=!0
        });
    g.jcarousel=function(a,c){
        this.options=g.extend({},q,c||{});
        this.autoStopped=this.locked=!1;
        this.buttonPrevState=this.buttonNextState=this.buttonPrev=this.buttonNext=this.list=this.clip=this.container=null;
        if(!c||c.rtl===void 0)this.options.rtl=(g(a).attr("dir")||g("html").attr("dir")||"").toLowerCase()=="rtl";
        this.wh=!this.options.vertical?"width":"height";
        this.lt=!this.options.vertical? this.options.rtl?"right":"left":"top";
        for(var b="",d=a.className.split(" "),f=0;f<d.length;f++)if(d[f].indexOf("jcarousel-skin")!=-1){
            g(a).removeClass(d[f]);
            b=d[f];
            break
        }
        a.nodeName.toUpperCase()=="UL"||a.nodeName.toUpperCase()=="OL"?(this.list=g(a),this.clip=this.list.parents(".jcarousel-clip"),this.container=this.list.parents(".jcarousel-container")):(this.container=g(a),this.list=this.container.find("ul,ol").eq(0),this.clip=this.container.find(".jcarousel-clip"));
        if(this.clip.size()===0)this.clip= this.list.wrap("<div></div>").parent();
        if(this.container.size()===0)this.container=this.clip.wrap("<div></div>").parent();
        b!==""&&this.container.parent()[0].className.indexOf("jcarousel-skin")==-1&&this.container.wrap('<div class=" '+b+'"></div>');
        this.buttonPrev=g(".jcarousel-prev",this.container);
        if(this.buttonPrev.size()===0&&this.options.buttonPrevHTML!==null)this.buttonPrev=g(this.options.buttonPrevHTML).appendTo(this.container);
        this.buttonPrev.addClass(this.className("jcarousel-prev"));
        this.buttonNext= g(".jcarousel-next",this.container);
        if(this.buttonNext.size()===0&&this.options.buttonNextHTML!==null)this.buttonNext=g(this.options.buttonNextHTML).appendTo(this.container);
        this.buttonNext.addClass(this.className("jcarousel-next"));
        this.clip.addClass(this.className("jcarousel-clip")).css({
            position:"relative"
        });
        this.list.addClass(this.className("jcarousel-list")).css({
            overflow:"hidden",
            position:"relative",
            top:0,
            margin:0,
            padding:0
        }).css(this.options.rtl?"right":"left",0);
        this.container.addClass(this.className("jcarousel-container")).css({
            position:"relative"
        });
        !this.options.vertical&&this.options.rtl&&this.container.addClass("jcarousel-direction-rtl").attr("dir","rtl");
        var j=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible):null,b=this.list.children("li"),e=this;
        if(b.size()>0){
            var h=0,i=this.options.offset;
            b.each(function(){
                e.format(this,i++);
                h+=e.dimension(this,j)
                });
            this.list.css(this.wh,h+100+"px");
            if(!c||c.size===void 0)this.options.size=b.size()
                }
                this.container.css("display","block");
        this.buttonNext.css("display","block");
        this.buttonPrev.css("display", "block");
        this.funcNext=function(){
            e.next()
            };

        this.funcPrev=function(){
            e.prev()
            };

        this.funcResize=function(){
            e.resizeTimer&&clearTimeout(e.resizeTimer);
            e.resizeTimer=setTimeout(function(){
                e.reload()
                },100)
            };

        this.options.initCallback!==null&&this.options.initCallback(this,"init");
        !m&&g.browser.safari?(this.buttons(!1,!1),g(window).bind("load.jcarousel",function(){
            e.setup()
            })):this.setup()
        };

    var f=g.jcarousel;
    f.fn=f.prototype={
        jcarousel:"0.2.8"
    };

    f.fn.extend=f.extend=g.extend;
    f.fn.extend({
        setup:function(){
            this.prevLast= this.prevFirst=this.last=this.first=null;
            this.animating=!1;
            this.tail=this.resizeTimer=this.timer=null;
            this.inTail=!1;
            if(!this.locked){
                this.list.css(this.lt,this.pos(this.options.offset)+"px");
                var a=this.pos(this.options.start,!0);
                this.prevFirst=this.prevLast=null;
                this.animate(a,!1);
                g(window).unbind("resize.jcarousel",this.funcResize).bind("resize.jcarousel",this.funcResize);
                this.options.setupCallback!==null&&this.options.setupCallback(this)
                }
            },
    reset:function(){
        this.list.empty();
        this.list.css(this.lt, "0px");
        this.list.css(this.wh,"10px");
        this.options.initCallback!==null&&this.options.initCallback(this,"reset");
        this.setup()
        },
    reload:function(){
        this.tail!==null&&this.inTail&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+this.tail);
        this.tail=null;
        this.inTail=!1;
        this.options.reloadCallback!==null&&this.options.reloadCallback(this);
        if(this.options.visible!==null){
            var a=this,c=Math.ceil(this.clipping()/this.options.visible),b=0,d=0;
            this.list.children("li").each(function(f){
                b+=a.dimension(this, c);
                f+1<a.first&&(d=b)
                });
            this.list.css(this.wh,b+"px");
            this.list.css(this.lt,-d+"px")
            }
            this.scroll(this.first,!1)
        },
    lock:function(){
        this.locked=!0;
        this.buttons()
        },
    unlock:function(){
        this.locked=!1;
        this.buttons()
        },
    size:function(a){
        if(a!==void 0)this.options.size=a,this.locked||this.buttons();
        return this.options.size
        },
    has:function(a,c){
        if(c===void 0||!c)c=a;
        if(this.options.size!==null&&c>this.options.size)c=this.options.size;
        for(var b=a;b<=c;b++){
            var d=this.get(b);
            if(!d.length||d.hasClass("jcarousel-item-placeholder"))return!1
                }
                return!0
        },
    get:function(a){
        return g(">.jcarousel-item-"+a,this.list)
        },
    add:function(a,c){
        var b=this.get(a),d=0,p=g(c);
        if(b.length===0)for(var j,e=f.intval(a),b=this.create(a);;){
            if(j=this.get(--e),e<=0||j.length){
                e<=0?this.list.prepend(b):j.after(b);
                break
            }
        }else d=this.dimension(b);
        p.get(0).nodeName.toUpperCase()=="LI"?(b.replaceWith(p),b=p):b.empty().append(c);
        this.format(b.removeClass(this.className("jcarousel-item-placeholder")),a);
        p=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible): null;
        d=this.dimension(b,p)-d;
        a>0&&a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))-d+"px");
        this.list.css(this.wh,f.intval(this.list.css(this.wh))+d+"px");
        return b
        },
    remove:function(a){
        var c=this.get(a);
        if(c.length&&!(a>=this.first&&a<=this.last)){
            var b=this.dimension(c);
            a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+b+"px");
            c.remove();
            this.list.css(this.wh,f.intval(this.list.css(this.wh))-b+"px")
            }
        },
next:function(){
    this.tail!==null&&!this.inTail?this.scrollTail(!1): this.scroll((this.options.wrap=="both"||this.options.wrap=="last")&&this.options.size!==null&&this.last==this.options.size?1:this.first+this.options.scroll)
    },
prev:function(){
    this.tail!==null&&this.inTail?this.scrollTail(!0):this.scroll((this.options.wrap=="both"||this.options.wrap=="first")&&this.options.size!==null&&this.first==1?this.options.size:this.first-this.options.scroll)
    },
scrollTail:function(a){
    if(!this.locked&&!this.animating&&this.tail){
        this.pauseAuto();
        var c=f.intval(this.list.css(this.lt)), c=!a?c-this.tail:c+this.tail;
        this.inTail=!a;
        this.prevFirst=this.first;
        this.prevLast=this.last;
        this.animate(c)
        }
    },
scroll:function(a,c){
    !this.locked&&!this.animating&&(this.pauseAuto(),this.animate(this.pos(a),c))
    },
pos:function(a,c){
    var b=f.intval(this.list.css(this.lt));
    if(this.locked||this.animating)return b;
    this.options.wrap!="circular"&&(a=a<1?1:this.options.size&&a>this.options.size?this.options.size:a);
    for(var d=this.first>a,g=this.options.wrap!="circular"&&this.first<=1?1:this.first,j=d?this.get(g): this.get(this.last),e=d?g:g-1,h=null,i=0,k=!1,l=0;d?--e>=a:++e<a;){
        h=this.get(e);
        k=!h.length;
        if(h.length===0&&(h=this.create(e).addClass(this.className("jcarousel-item-placeholder")),j[d?"before":"after"](h),this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size)))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)));
        j=h;
        l=this.dimension(h);
        k&&(i+=l);
        if(this.first!==null&&(this.options.wrap=="circular"||e>=1&&(this.options.size===null||e<= this.options.size)))b=d?b+l:b-l
            }
            for(var g=this.clipping(),m=[],o=0,n=0,j=this.get(a-1),e=a;++o;){
        h=this.get(e);
        k=!h.length;
        if(h.length===0){
            h=this.create(e).addClass(this.className("jcarousel-item-placeholder"));
            if(j.length===0)this.list.prepend(h);else j[d?"before":"after"](h);
            if(this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)))
                }
                j=h;
        l=this.dimension(h);
        if(l===0)throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...");
        this.options.wrap!="circular"&&this.options.size!==null&&e>this.options.size?m.push(h):k&&(i+=l);
        n+=l;
        if(n>=g)break;
        e++
    }
    for(h=0;h<m.length;h++)m[h].remove();
    i>0&&(this.list.css(this.wh,this.dimension(this.list)+i+"px"),d&&(b-=i,this.list.css(this.lt,f.intval(this.list.css(this.lt))-i+"px")));
    i=a+o-1;
    if(this.options.wrap!="circular"&&this.options.size&&i>this.options.size)i=this.options.size;
    if(e>i){
        o=0;
        e=i;
        for(n=0;++o;){
            h=this.get(e--);
            if(!h.length)break;
            n+=this.dimension(h);
            if(n>=g)break
        }
        }
        e=i-o+ 1;
this.options.wrap!="circular"&&e<1&&(e=1);
    if(this.inTail&&d)b+=this.tail,this.inTail=!1;
    this.tail=null;
    if(this.options.wrap!="circular"&&i==this.options.size&&i-o+1>=1&&(d=f.intval(this.get(i).css(!this.options.vertical?"marginRight":"marginBottom")),n-d>g))this.tail=n-g-d;
    if(c&&a===this.options.size&&this.tail)b-=this.tail,this.inTail=!0;
    for(;a-- >e;)b+=this.dimension(this.get(a));
    this.prevFirst=this.first;
    this.prevLast=this.last;
    this.first=e;
    this.last=i;
    return b
    },
animate:function(a,c){
    if(!this.locked&& !this.animating){
        this.animating=!0;
        var b=this,d=function(){
            b.animating=!1;
            a===0&&b.list.css(b.lt,0);
            !b.autoStopped&&(b.options.wrap=="circular"||b.options.wrap=="both"||b.options.wrap=="last"||b.options.size===null||b.last<b.options.size||b.last==b.options.size&&b.tail!==null&&!b.inTail)&&b.startAuto();
            b.buttons();
            b.notify("onAfterAnimation");
            if(b.options.wrap=="circular"&&b.options.size!==null)for(var c=b.prevFirst;c<=b.prevLast;c++)c!==null&&!(c>=b.first&&c<=b.last)&&(c<1||c>b.options.size)&&b.remove(c)
                };
        this.notify("onBeforeAnimation");
        if(!this.options.animation||c===!1)this.list.css(this.lt,a+"px"),d();
        else{
            var f=!this.options.vertical?this.options.rtl?{
                right:a
            }:{
                left:a
            }:{
                top:a
            },d={
                duration:this.options.animation,
                easing:this.options.easing,
                complete:d
            };

            if(g.isFunction(this.options.animationStepCallback))d.step=this.options.animationStepCallback;
            this.list.animate(f,d)
            }
        }
},
startAuto:function(a){
    if(a!==void 0)this.options.auto=a;
    if(this.options.auto===0)return this.stopAuto();
    if(this.timer===null){
        this.autoStopped= !1;
        var c=this;
        this.timer=window.setTimeout(function(){
            c.next()
            },this.options.auto*1E3)
        }
    },
stopAuto:function(){
    this.pauseAuto();
    this.autoStopped=!0
    },
pauseAuto:function(){
    if(this.timer!==null)window.clearTimeout(this.timer),this.timer=null
        },
buttons:function(a,c){
    if(a==null&&(a=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="first"||this.options.size===null||this.last<this.options.size),!this.locked&&(!this.options.wrap||this.options.wrap=="first")&&this.options.size!==null&& this.last>=this.options.size))a=this.tail!==null&&!this.inTail;
    if(c==null&&(c=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="last"||this.first>1),!this.locked&&(!this.options.wrap||this.options.wrap=="last")&&this.options.size!==null&&this.first==1))c=this.tail!==null&&this.inTail;
    var b=this;
    this.buttonNext.size()>0?(this.buttonNext.unbind(this.options.buttonNextEvent+".jcarousel",this.funcNext),a&&this.buttonNext.bind(this.options.buttonNextEvent+".jcarousel",this.funcNext), this.buttonNext[a?"removeClass":"addClass"](this.className("jcarousel-next-disabled")).attr("disabled",a?!1:!0),this.options.buttonNextCallback!==null&&this.buttonNext.data("jcarouselstate")!=a&&this.buttonNext.each(function(){
        b.options.buttonNextCallback(b,this,a)
        }).data("jcarouselstate",a)):this.options.buttonNextCallback!==null&&this.buttonNextState!=a&&this.options.buttonNextCallback(b,null,a);
    this.buttonPrev.size()>0?(this.buttonPrev.unbind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev), c&&this.buttonPrev.bind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev),this.buttonPrev[c?"removeClass":"addClass"](this.className("jcarousel-prev-disabled")).attr("disabled",c?!1:!0),this.options.buttonPrevCallback!==null&&this.buttonPrev.data("jcarouselstate")!=c&&this.buttonPrev.each(function(){
        b.options.buttonPrevCallback(b,this,c)
        }).data("jcarouselstate",c)):this.options.buttonPrevCallback!==null&&this.buttonPrevState!=c&&this.options.buttonPrevCallback(b,null,c);
    this.buttonNextState= a;
    this.buttonPrevState=c
    },
notify:function(a){
    var c=this.prevFirst===null?"init":this.prevFirst<this.first?"next":"prev";
    this.callback("itemLoadCallback",a,c);
    this.prevFirst!==this.first&&(this.callback("itemFirstInCallback",a,c,this.first),this.callback("itemFirstOutCallback",a,c,this.prevFirst));
    this.prevLast!==this.last&&(this.callback("itemLastInCallback",a,c,this.last),this.callback("itemLastOutCallback",a,c,this.prevLast));
    this.callback("itemVisibleInCallback",a,c,this.first,this.last,this.prevFirst, this.prevLast);
    this.callback("itemVisibleOutCallback",a,c,this.prevFirst,this.prevLast,this.first,this.last)
    },
callback:function(a,c,b,d,f,j,e){
    if(!(this.options[a]==null||typeof this.options[a]!="object"&&c!="onAfterAnimation")){
        var h=typeof this.options[a]=="object"?this.options[a][c]:this.options[a];
        if(g.isFunction(h)){
            var i=this;
            if(d===void 0)h(i,b,c);
            else if(f===void 0)this.get(d).each(function(){
                h(i,this,d,b,c)
                });else for(var a=function(a){
                i.get(a).each(function(){
                    h(i,this,a,b,c)
                    })
                },k=d;k<=f;k++)k!== null&&!(k>=j&&k<=e)&&a(k)
                }
            }
},
create:function(a){
    return this.format("<li></li>",a)
    },
format:function(a,c){
    for(var a=g(a),b=a.get(0).className.split(" "),d=0;d<b.length;d++)b[d].indexOf("jcarousel-")!=-1&&a.removeClass(b[d]);
    a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-"+c)).css({
        "float":this.options.rtl?"right":"left",
        "list-style":"none"
    }).attr("jcarouselindex",c);
    return a
    },
className:function(a){
    return a+" "+a+(!this.options.vertical?"-horizontal":"-vertical")
    },
dimension:function(a,c){
    var b=g(a);
    if(c==null)return!this.options.vertical?b.outerWidth(!0)||f.intval(this.options.itemFallbackDimension):b.outerHeight(!0)||f.intval(this.options.itemFallbackDimension);
    else{
        var d=!this.options.vertical?c-f.intval(b.css("marginLeft"))-f.intval(b.css("marginRight")):c-f.intval(b.css("marginTop"))-f.intval(b.css("marginBottom"));
        g(b).css(this.wh,d+"px");
        return this.dimension(b)
        }
    },
clipping:function(){
    return!this.options.vertical?this.clip[0].offsetWidth-f.intval(this.clip.css("borderLeftWidth"))- f.intval(this.clip.css("borderRightWidth")):this.clip[0].offsetHeight-f.intval(this.clip.css("borderTopWidth"))-f.intval(this.clip.css("borderBottomWidth"))
    },
index:function(a,c){
    if(c==null)c=this.options.size;
    return Math.round(((a-1)/c-Math.floor((a-1)/c))*c)+1
    }
});
f.extend({
    defaults:function(a){
        return g.extend(q,a||{})
        },
    intval:function(a){
        a=parseInt(a,10);
        return isNaN(a)?0:a
        },
    windowLoaded:function(){
        m=!0
        }
    });
g.fn.jcarousel=function(a){
    if(typeof a=="string"){
        var c=g(this).data("jcarousel"),b=Array.prototype.slice.call(arguments, 1);
        return c[a].apply(c,b)
        }else return this.each(function(){
        var b=g(this).data("jcarousel");
        b?(a&&g.extend(b.options,a),b.reload()):g(this).data("jcarousel",new f(this,a))
        })
    }
    })(jQuery);

/*  5/20/2011
		PikaChoose
	Jquery plugin for photo galleries
    Copyright (C) 2011 Jeremy Fry

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
(function($){
    var defaults={
        autoPlay:true,
        speed:5000,
        text:{
            play:"",
            stop:"",
            previous:"",
            next:""
        },
        transition:[1],
        showCaption:true,
        IESafe:true,
        showTooltips:false,
        carousel:false,
        carouselVertical:false,
        animationFinished:null,
        buildFinished:null,
        bindFinished:null,
        startOn:0,
        thumbOpacity:0.4,
        hoverPause:false
    };

    $.fn.PikaChoose=function(o){
        return this.each(function(){
            $(this).data('pikachoose',new $pc(this,o))
            })
        };

    $.PikaChoose=function(e,o){
        this.options=$.extend({},defaults,o||{});
        this.list=null;
        this.image=null;
        this.anchor=null;
        this.caption=null;
        this.imgNav=null;
        this.imgPlay=null;
        this.imgPrev=null;
        this.imgNext=null;
        this.textNext=null;
        this.textPrev=null;
        this.previous=null;
        this.next=null;
        this.aniWrap=null;
        this.aniDiv=null;
        this.aniImg=null;
        this.thumbs=null;
        this.transition=null;
        this.active=null;
        this.tooltip=null;
        this.animating=false;
        this.stillOut=null;
        this.counter=null;
        this.timeOut=null;
        if(typeof(this.options.data)!="undefined"){
            e=$("<ul></ul>").appendTo(e);
            $.each(this.options.data,function(){
                if(typeof(this.link)!="undefined"){
                    var tmp=$("<li><a href='"+this.link+"'><img></a></li>").appendTo(e);
                    if(typeof(this.title)!="undefined"){
                        tmp.find('a').attr('title',this.title)
                        }
                    }else{
                var tmp=$("<li><img></li>").appendTo(e)
                }
                if(typeof(this.caption)!="undefined"){
                tmp.append("<span>"+this.caption+"</span>")
                }
                if(typeof(this.thumbnail)!="undefined"){
                tmp.find('img').attr('ref',this.image);
                tmp.find('img').attr('src',this.thumbnail)
                }else{
                tmp.find('img').attr('src',this.image)
                }
            })
    }
    if(e.nodeName=='UL'||e.nodeName=='OL'||e instanceof jQuery){
    this.list=$(e);
    this.build();
    this.bindEvents()
    }else{
    return
}
var y=0;
var x=0;
for(var t=0;t<25;t++){
    var a='<div col="'+y+'" row="'+x+'"></div>';
    this.aniDiv.append(a);
    y++;
    if(y==5){
        x++;
        y=0
        }
    }
};

var $pc=$.PikaChoose;
$pc.fn=$pc.prototype={
    pikachoose:'4.3.1'
};

$.fn.pikachoose=$.fn.PikaChoose;
$pc.fn.extend=$pc.extend=$.extend;
$pc.fn.extend({
    build:function(){
        this.step=0;
        this.wrap=$("<div class='pika-stage'></div>").insertBefore(this.list);
        this.image=$("<img>").appendTo(this.wrap);
        this.imgNav=$("<div class='pika-imgnav'></div>").insertAfter(this.image);
        this.imgPlay=$("<a></a>").appendTo(this.imgNav);
        this.counter=$("<span class='pika-counter'></span>").appendTo(this.imgNav);
        if(this.options.autoPlay){
            this.imgPlay.addClass('pause')
            }else{
            this.imgPlay.addClass('play')
            }
            this.imgPrev=$("<a class='previous'></a>").insertAfter(this.imgPlay);
        this.imgNext=$("<a class='next'></a>").insertAfter(this.imgPrev);
        this.caption=$("<div class='caption'></div>").insertAfter(this.imgNav).hide();
        this.tooltip=$("<div class='pika-tooltip'></div>").insertAfter(this.list).hide();
        this.aniWrap=$("<div class='pika-aniwrap'></div>").insertAfter(this.caption);
        this.aniImg=$("<img>").appendTo(this.aniWrap).hide();
        this.aniDiv=$("<div class='pika-ani'></div>").appendTo(this.aniWrap);
        this.textNav=$("<div class='pika-textnav'></div>").insertAfter(this.aniWrap);
        this.textPrev=$("<a class='previous'>"+this.options.text.previous+"</a>").appendTo(this.textNav);
        this.textNext=$("<a class='next'>"+this.options.text.next+"</a>").appendTo(this.textNav);
        this.list.addClass('pika-thumbs');
        this.list.children('li').wrapInner("<div class='clip' />");
        this.thumbs=this.list.find('img');
        this.active=this.thumbs.eq(this.options.startOn);
        this.finishAnimating({
            'source':this.active.attr('ref')||this.active.attr('src'),
            'caption':this.active.parents('li:first').find('span:first').html(),
            'clickThrough':this.active.parent().attr('href')||"",
            'clickThroughTitle':this.active.parent().attr('title')||""
            });
        var self=this;
        this.thumbs.each(function(){
            self.createThumb($(this),self)
            });
        if(this.options.carousel){
            this.list.jcarousel({
                vertical:this.options.carouselVertical,
                initCallback:function(carousel){
                    jQuery(carousel.list).find('img').click(function(){
                        var clicked=parseInt(jQuery(this).parents('.jcarousel-item').attr('jcarouselindex'));
                        var last=(jQuery(this).parents('ul').find('li:last').index()==clicked-1)?true:false;
                        if(!last){
                            clicked=(clicked-2<=0)?0:clicked-2
                            }
                            clicked++;
                        carousel.scroll(clicked)
                        })
                    }
                })
        }
        if(typeof(this.options.buildFinished)=='function'){
        this.options.buildFinished(this)
        }
    },
createThumb:function(ele){
    var self=ele;
    var that=this;
    self.hide();
    $.data(ele[0],'clickThrough',self.parent('a').attr('href')||"");
    $.data(ele[0],'clickThroughTitle',self.parent('a').attr('title')||"");
    if(self.parent('a').length>0){
        self.unwrap()
        }
        $.data(ele[0],'caption',self.next('span').html()||"");
    self.next('span').remove();
    $.data(ele[0],'source',self.attr('ref')||self.attr('src'));
    $.data(ele[0],'order',self.closest('ul').find('li').index(self.parents('li')));
    var data=$.data(ele[0]);
    $('<img />').bind('load',{
        data:data
    },function(){
        if(typeof(that.options.buildThumbStart)=='function'){
            that.options.buildThumbStart(that)
            }
            var img=$(this);
        var w=this.width;
        var h=this.height;
        if(w===0){
            w=img.attr("width")
            }
            if(h===0){
            h=img.attr("height")
            }
            var rw=parseInt(self.parents('.clip').css('width').slice(0,-2))/w;
        var rh=parseInt(self.parents('.clip').css('height').slice(0,-2))/h;
        var ratio;
        if(rw<rh){
            ratio=rh;
            var left=((w*ratio-parseInt(self.parents('.clip').css('width').slice(0,-2)))/2)*-1;
            left=Math.round(left);
            self.css({
                left:left
            })
            }else{
            ratio=rw;
            self.css({
                top:0
            })
            }
            var width=Math.round(w*ratio);
        var height=Math.round(h*ratio);
        self.css("position","relative");
        var imgcss={
            width:width+"px",
            height:height+"px"
            };

        self.css(imgcss);
        self.hover(function(e){
            clearTimeout(that.stillOut);
            $(this).stop(true,true).fadeTo(250,1);
            if(!that.options.showTooltips){
                return
            }
            that.tooltip.show().stop(true,true).html(data.caption).animate({
                top:$(this).parent().position().top,
                left:$(this).parent().position().left,
                opacity:1.0
            },'fast')
            },function(e){
            if(!$(this).hasClass("active")){
                $(this).stop(true,true).fadeTo(250,that.options.thumbOpacity);
                that.stillOut=setTimeout(that.hideTooltip,700)
                }
            });
    if(data.order==that.options.startOn){
        self.fadeTo(250,1);
        self.addClass('active');
        self.parents('li').eq(0).addClass('active')
        }else{
        self.fadeTo(250,that.options.thumbOpacity)
        }
        if(typeof(that.options.buildThumbFinish)=='function'){
        that.options.buildThumbFinish(that)
        }
    }).attr('src',self.attr('src'))
},
bindEvents:function(){
    this.thumbs.bind('click',{
        self:this
    },this.imgClick);
    this.imgNext.bind('click',{
        self:this
    },this.nextClick);
    this.textNext.bind('click',{
        self:this
    },this.nextClick);
    this.imgPrev.bind('click',{
        self:this
    },this.prevClick);
    this.textPrev.bind('click',{
        self:this
    },this.prevClick);
    this.imgPlay.bind('click',{
        self:this
    },this.playClick);
    this.wrap.bind('mouseenter',{
        self:this
    },function(e){
        e.data.self.imgNav.stop(true,true).fadeIn('slow');
        if(e.data.self.options.hoverPause==true){
            clearTimeout(e.data.self.timeOut)
            }
        });
this.wrap.bind('mouseleave',{
    self:this
},function(e){
    e.data.self.imgNav.stop(true,true).fadeOut('slow');
    if(e.data.self.options.autoPlay==true&&e.data.self.options.hoverPause){
        e.data.self.timeOut=setTimeout((function(self){
            return function(){
                self.nextClick()
                }
            })(e.data.self),e.data.self.options.speed)
    }
});
this.tooltip.bind('mouseenter',{
    self:this
},function(e){
    clearTimeout(e.data.self.stillOut)
    });
this.tooltip.bind('mouseleave',{
    self:this
},function(e){
    e.data.self.stillOut=setTimeout(e.data.self.hideTooltip,700)
    });
if(typeof(this.options.bindsFinished)=='function'){
    this.options.bindsFinished(this)
    }
},
hideTooltip:function(e){
    $(".pika-tooltip").animate({
        opacity:0.01
    })
    },
imgClick:function(e,x){
    var self=e.data.self;
    var data=$.data(this);
    if(self.animating){
        return
    }
    if(typeof(x)=='undefined'||x.how!="auto"){
        if(self.options.autoPlay){
            self.imgPlay.trigger('click')
            }
        }else{
    if(self.options.autoPlay==false){
        return false
        }
    }
self.caption.fadeOut('slow');
self.animating=true;
self.active.fadeTo(300,self.options.thumbOpacity).removeClass('active');
self.active.parents('.active').eq(0).removeClass('active');
self.active=$(this);
self.active.addClass('active').fadeTo(200,1);
self.active.parents('li').eq(0).addClass('active');
$('<img />').bind('load',{
    self:self,
    data:data
},function(){
    self.aniDiv.css({
        height:self.image.height(),
        width:self.image.width()
        }).fadeIn('fast');
    self.aniDiv.children('div').css({
        'width':'20%',
        'height':'20%',
        'float':'left'
    });
    var n=0;
    if(self.options.transition[0]==-1){
        n=Math.floor(Math.random()*7)+1
        }else{
        n=self.options.transition[self.step];
        self.step++;
        if(self.step>=self.options.transition.length){
            self.step=0
            }
        }
    if(self.options.IESafe&&$.browser.msie){
    n=1
    }
    self.doAnimation(n,data)
    }).attr('src',$.data(this).source)
},
doAnimation:function(n,data){
    var self=this;
    self.image.stop(true,false);
    self.caption.stop().fadeOut();
    var aWidth=self.aniDiv.children('div').eq(0).width();
    var aHeight=self.aniDiv.children('div').eq(0).height();
    var img=new Image();
    $(img).attr('src',data.source);
    if(img.height!=self.image.height()||img.width!=self.image.width()){
        if(n!=0&&n!=1&&n!=7){
            n=1
            }
        }
    self.aniDiv.css({
    height:img.height,
    width:img.width
    });
self.aniDiv.children().each(function(){
    var div=$(this);
    var xOffset=Math.floor(div.parent().width()/5)*div.attr('col');
    var yOffset=Math.floor(div.parent().height()/5)*div.attr('row');
    div.css({
        'background':'url('+data.source+') -'+xOffset+'px -'+yOffset+'px',
        'width':'0px',
        'height':'0px',
        'position':'absolute',
        'top':yOffset+'px',
        'left':xOffset+'px',
        'float':'none'
    })
    });
self.aniDiv.hide();
self.aniImg.hide();
switch(n){
    case 0:
        self.image.stop(true,true).fadeOut('slow',function(){
        self.image.attr('src',data.source).fadeIn('slow',function(){
            self.finishAnimating(data)
            })
        });
    break;
    case 1:
        self.aniDiv.hide();
        self.aniImg.height(self.image.height()).hide().attr('src',data.source);
        $.when(self.image.fadeOut('slow'),self.aniImg.eq(0).fadeIn('slow')).done(function(){
        self.finishAnimating(data)
        });
    break;
    case 2:
        self.aniDiv.show().children().hide().each(function(index){
        var delay=index*30;
        $(this).css({
            opacity:0.1
        }).show().delay(delay).animate({
            opacity:1,
            "width":aWidth,
            "height":aHeight
        },200,'linear',function(){
            if(self.aniDiv.find("div").index(this)==24){
                self.finishAnimating(data)
                }
            })
    });
    break;
case 3:
    self.aniDiv.show().children("div:lt(5)").hide().each(function(index){
    var delay=$(this).attr('col')*100;
    $(this).css({
        opacity:0.1,
        "width":aWidth
    }).show().delay(delay).animate({
        opacity:1,
        "height":self.image.height()
        },700,'linear',function(){
        if(self.aniDiv.find(" div").index(this)==4){
            self.finishAnimating(data)
            }
        })
});
break;
case 4:
    self.aniDiv.show().children().hide().each(function(index){
    if(index>4){
        return
    }
    var delay=$(this).attr('col')*10;
    aHeight=self.gapper($(this),aHeight);
    $(this).css({
        opacity:0.1,
        "height":"100%"
    }).show().animate({
        opacity:1,
        "width":aWidth
    },500,'linear',function(){
        if(self.aniDiv.find(" div").index(this)==4){
            self.finishAnimating(data)
            }
        })
});
break;
case 5:
    self.aniDiv.show().children().show().each(function(index){
    var delay=index*Math.floor(Math.random()*5)*7;
    aHeight=self.gapper($(this),aHeight);
    if($(".animation div").index(this)==24){
        delay=600
        }
        $(this).css({
        "height":aHeight,
        "width":aWidth,
        "opacity":.01
    }).delay(delay).animate({
        "opacity":1
    },600,function(){
        if(self.aniDiv.find(" div").index(this)==24){
            self.finishAnimating(data)
            }
        })
});
break;
case 6:
    self.aniDiv.height(self.image.height()).hide().css({
    'background':'url('+data.source+') top left no-repeat'
    });
self.aniDiv.children('div').hide();
    self.aniDiv.css({
    width:0
}).show().animate({
    width:self.image.width()
    },'slow',function(){
    self.finishAnimating(data);
    self.aniDiv.css({
        'background':'transparent'
    })
    });
break;
case 7:
    self.wrap.css({
    overflow:'hidden'
});
self.aniImg.height(self.image.height()).hide().attr('src',data.source);
    self.aniDiv.hide();
    self.image.css({
    position:'relative'
}).animate({
    left:"-"+self.wrap.outerWidth()+"px"
    });
self.aniImg.show();
    self.aniWrap.css({
    left:self.wrap.outerWidth()
    }).show().animate({
    left:"0px"
},'slow',function(){
    self.finishAnimating(data)
    });
break
}
},
finishAnimating:function(data){
    this.animating=false;
    this.image.attr('src',data.source);
    this.image.css({
        left:"0"
    });
    this.image.show();
    var self=this;
    $('<img />').bind('load',function(){
        self.aniImg.hide();
        self.aniDiv.hide()
        }).attr('src',data.source);
    var cur=this.list.find('img').index(this.active);
    cur++;
    var total=this.list.find('img').length;
    this.counter.html(cur+"/"+total);
    if(data.clickThrough!=""){
        if(this.anchor==null){
            this.anchor=this.image.wrap("<a>").parent()
            }
            this.anchor.attr('href',data.clickThrough);
        this.anchor.attr('title',data.clickThroughTitle)
        }else{
        if(this.image.parent('a').length>0){
            this.image.unwrap()
            }
            this.anchor=null
        }
        if(this.options.showCaption&&data.caption!=""&&data.caption!=null){
        this.caption.html(data.caption).fadeTo('slow',1)
        }
        if(this.options.autoPlay==true){
        var self=this;
        this.timeOut=setTimeout((function(self){
            return function(){
                self.nextClick()
                }
            })(this),this.options.speed,this.timeOut)
    }
    if(typeof(this.options.animationFinished)=='function'){
    this.options.animationFinished(this)
    }
},
gapper:function(ele,aHeight){
    if(ele.attr('row')==9&&ele.attr('col')==0){
        var gap=ani_divs.height()-(aHeight*9);
        return gap
        }
        return aHeight
    },
nextClick:function(e){
    var how="natural";
    try{
        var self=e.data.self;
        if(typeof(e.data.self.options.next)=='function'){
            e.data.self.options.next(this)
            }
        }catch(err){
    var self=this;
    how="auto"
    }
    var next=self.active.parents('li:first').next().find('img');
if(next.length==0){
    next=self.list.find('img').eq(0)
    };

next.trigger('click',{
    how:how
})
},
prevClick:function(e){
    if(typeof(e.data.self.options.previous)=='function'){
        e.data.self.options.previous(this)
        }
        var self=e.data.self;
    var prev=self.active.parents('li:first').prev().find('img');
    if(prev.length==0){
        prev=self.list.find('img:last')
        };

    prev.trigger('click')
    },
playClick:function(e){
    var self=e.data.self;
    self.options.autoPlay=!self.options.autoPlay;
    self.imgPlay.toggleClass('play').toggleClass('pause');
    if(self.options.autoPlay){
        self.nextClick()
        }
    }
})
})(jQuery);


 /* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 3.1.2
------------------------------------------------------------------------- */

(function($){
    $.prettyPhoto={
        version:'3.1.2'
    };

    $.fn.prettyPhoto=function(pp_settings){
        pp_settings=jQuery.extend({
            animation_speed:'fast',
            slideshow:5000,
            autoplay_slideshow:false,
            opacity:0.80,
            show_title:true,
            allow_resize:true,
            default_width:500,
            default_height:344,
            counter_separator_label:'/',
            theme:'pp_default',
            horizontal_padding:20,
            hideflash:false,
            wmode:'opaque',
            autoplay:true,
            modal:false,
            deeplinking:true,
            overlay_gallery:true,
            keyboard_shortcuts:true,
            changepicturecallback:function(){},
            callback:function(){},
            ie6_fallback:true,
            markup:'<div class="pp_pic_holder"><div class="ppt">&nbsp;</div><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content_container"><div class="pp_left"><div class="pp_right"><div class="pp_content"><div class="pp_loaderIcon"></div><div class="pp_fade"><a href="#" class="pp_expand" title="Expand the image">Expand</a><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res"></div><div class="pp_details"><div class="pp_nav"><a href="#" class="pp_arrow_previous">Previous</a><p class="currentTextHolder">0/0</p><a href="#" class="pp_arrow_next">Next</a></div><p class="pp_description"></p>{pp_social}<a class="pp_close" href="#">Close</a></div></div></div></div></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div><div class="pp_overlay"></div>',
            gallery_markup:'<div class="pp_gallery"><a href="#" class="pp_arrow_previous">Previous</a><div><ul>{gallery}</ul></div><a href="#" class="pp_arrow_next">Next</a></div>',
            image_markup:'<img id="fullResImage" src="{path}" />',
            flash_markup:'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
            quicktime_markup:'<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
            iframe_markup:'<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
            inline_markup:'<div class="pp_inline">{content}</div>',
            custom_markup:'',
            social_tools:'<div class="pp_social"><div class="twitter"><a href="http://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="http://www.facebook.com/plugins/like.php?locale=en_US&href='+location.href+'&amp;layout=button_count&amp;show_faces=true&amp;width=500&amp;action=like&amp;font&amp;colorscheme=light&amp;height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div></div>'
            },pp_settings);
        var matchedObjects=this,percentBased=false,pp_dimensions,pp_open,pp_contentHeight,pp_contentWidth,pp_containerHeight,pp_containerWidth,windowHeight=$(window).height(),windowWidth=$(window).width(),pp_slideshow;
        doresize=true,scroll_pos=_get_scroll();
        $(window).unbind('resize.prettyphoto').bind('resize.prettyphoto',function(){
            _center_overlay();
            _resize_overlay();
        });
        if(pp_settings.keyboard_shortcuts){
            $(document).unbind('keydown.prettyphoto').bind('keydown.prettyphoto',function(e){
                if(typeof $pp_pic_holder!='undefined'){
                    if($pp_pic_holder.is(':visible')){
                        switch(e.keyCode){
                            case 37:
                                $.prettyPhoto.changePage('previous');
                                e.preventDefault();
                                break;
                            case 39:
                                $.prettyPhoto.changePage('next');
                                e.preventDefault();
                                break;
                            case 27:
                                if(!settings.modal)
                                $.prettyPhoto.close();
                            e.preventDefault();
                                break;
                        };

                };

            };

    });
};

$.prettyPhoto.initialize=function(){
    settings=pp_settings;
    if(settings.theme=='pp_default')settings.horizontal_padding=16;
    if(settings.ie6_fallback&&$.browser.msie&&parseInt($.browser.version)==6)settings.theme="light_square";
    theRel=$(this).attr('rel');
    galleryRegExp=/\[(?:.*)\]/;
    isSet=(galleryRegExp.exec(theRel))?true:false;
    pp_images=(isSet)?jQuery.map(matchedObjects,function(n,i){
        if($(n).attr('rel').indexOf(theRel)!=-1)return $(n).attr('href');
    }):$.makeArray($(this).attr('href'));
    pp_titles=(isSet)?jQuery.map(matchedObjects,function(n,i){
        if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).find('img').attr('alt'))?$(n).find('img').attr('alt'):"";
    }):$.makeArray($(this).find('img').attr('alt'));
    pp_descriptions=(isSet)?jQuery.map(matchedObjects,function(n,i){
        if($(n).attr('rel').indexOf(theRel)!=-1)return($(n).attr('title'))?$(n).attr('title'):"";
    }):$.makeArray($(this).attr('title'));
    set_position=jQuery.inArray($(this).attr('href'),pp_images);
    rel_index=(isSet)?set_position:$("a[rel^='"+theRel+"']").index($(this));
    _build_overlay(this);
    if(settings.allow_resize)
        $(window).bind('scroll.prettyphoto',function(){
            _center_overlay();
        });
    $.prettyPhoto.open();
    return false;
}
$.prettyPhoto.open=function(event){
    if(typeof settings=="undefined"){
        settings=pp_settings;
        if($.browser.msie&&$.browser.version==6)settings.theme="light_square";
        pp_images=$.makeArray(arguments[0]);
        pp_titles=(arguments[1])?$.makeArray(arguments[1]):$.makeArray("");
        pp_descriptions=(arguments[2])?$.makeArray(arguments[2]):$.makeArray("");
        isSet=(pp_images.length>1)?true:false;
        set_position=0;
        _build_overlay(event.target);
    }
    if($.browser.msie&&$.browser.version==6)$('select').css('visibility','hidden');
    if(settings.hideflash)$('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','hidden');
    _checkPosition($(pp_images).size());
    $('.pp_loaderIcon').show();
    if($ppt.is(':hidden'))$ppt.css('opacity',0).show();
    $pp_overlay.show().fadeTo(settings.animation_speed,settings.opacity);
    $pp_pic_holder.find('.currentTextHolder').text((set_position+1)+settings.counter_separator_label+$(pp_images).size());
    if(pp_descriptions[set_position]!=""){
        $pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position]));
    }else{
        $pp_pic_holder.find('.pp_description').hide();
    }
    movie_width=(parseFloat(getParam('width',pp_images[set_position])))?getParam('width',pp_images[set_position]):settings.default_width.toString();
    movie_height=(parseFloat(getParam('height',pp_images[set_position])))?getParam('height',pp_images[set_position]):settings.default_height.toString();
    percentBased=false;
    if(movie_height.indexOf('%')!=-1){
        movie_height=parseFloat(($(window).height()*parseFloat(movie_height)/100)-150);
        percentBased=true;
    }
    if(movie_width.indexOf('%')!=-1){
        movie_width=parseFloat(($(window).width()*parseFloat(movie_width)/100)-150);
        percentBased=true;
    }
    $pp_pic_holder.fadeIn(function(){
        (settings.show_title&&pp_titles[set_position]!=""&&typeof pp_titles[set_position]!="undefined")?$ppt.html(unescape(pp_titles[set_position])):$ppt.html('&nbsp;');
        imgPreloader="";
        skipInjection=false;
        switch(_getFileType(pp_images[set_position])){
            case'image':
                imgPreloader=new Image();
                nextImage=new Image();
                if(isSet&&set_position<$(pp_images).size()-1)nextImage.src=pp_images[set_position+1];
                prevImage=new Image();
                if(isSet&&pp_images[set_position-1])prevImage.src=pp_images[set_position-1];
                $pp_pic_holder.find('#pp_full_res')[0].innerHTML=settings.image_markup.replace(/{path}/g,pp_images[set_position]);
                imgPreloader.onload=function(){
                pp_dimensions=_fitToViewport(imgPreloader.width,imgPreloader.height);
                _showContent();
            };

            imgPreloader.onerror=function(){
                alert('Image cannot be loaded. Make sure the path is correct and image exist.');
                $.prettyPhoto.close();
            };

            imgPreloader.src=pp_images[set_position];
            break;
            case'youtube':
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                movie='http://www.youtube.com/embed/'+getParam('v',pp_images[set_position]);
                (getParam('rel',pp_images[set_position]))?movie+="?rel="+getParam('rel',pp_images[set_position]):movie+="?rel=1";
                if(settings.autoplay)movie+="&autoplay=1";
                toInject=settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie);
                break;
            case'vimeo':
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                movie_id=pp_images[set_position];
                var regExp=/http:\/\/(www\.)?vimeo.com\/(\d+)/;
                var match=movie_id.match(regExp);
                movie='http://player.vimeo.com/video/'+match[2]+'?title=0&amp;byline=0&amp;portrait=0';
                if(settings.autoplay)movie+="&autoplay=1;";
                vimeo_width=pp_dimensions['width']+'/embed/?moog_width='+pp_dimensions['width'];
                toInject=settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,movie);
                break;
            case'quicktime':
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                pp_dimensions['height']+=15;
                pp_dimensions['contentHeight']+=15;
                pp_dimensions['containerHeight']+=15;
                toInject=settings.quicktime_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay);
                break;
            case'flash':
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                flash_vars=pp_images[set_position];
                flash_vars=flash_vars.substring(pp_images[set_position].indexOf('flashvars')+10,pp_images[set_position].length);
                filename=pp_images[set_position];
                filename=filename.substring(0,filename.indexOf('?'));
                toInject=settings.flash_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);
                break;
            case'iframe':
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                frame_url=pp_images[set_position];
                frame_url=frame_url.substr(0,frame_url.indexOf('iframe')-1);
                toInject=settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,frame_url);
                break;
            case'ajax':
                doresize=false;
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                doresize=true;
                skipInjection=true;
                $.get(pp_images[set_position],function(responseHTML){
                toInject=settings.inline_markup.replace(/{content}/g,responseHTML);
                $pp_pic_holder.find('#pp_full_res')[0].innerHTML=toInject;
                _showContent();
            });
            break;
            case'custom':
                pp_dimensions=_fitToViewport(movie_width,movie_height);
                toInject=settings.custom_markup;
                break;
            case'inline':
                myClone=$(pp_images[set_position]).clone().append('<br clear="all" />').css({
                'width':settings.default_width
                }).wrapInner('<div id="pp_full_res"><div class="pp_inline"></div></div>').appendTo($('body')).show();
                doresize=false;
                pp_dimensions=_fitToViewport($(myClone).width(),$(myClone).height());
                doresize=true;
                $(myClone).remove();
                toInject=settings.inline_markup.replace(/{content}/g,$(pp_images[set_position]).html());
                break;
        };

        if(!imgPreloader&&!skipInjection){
            $pp_pic_holder.find('#pp_full_res')[0].innerHTML=toInject;
            _showContent();
        };

    });
return false;
};

$.prettyPhoto.changePage=function(direction){
    currentGalleryPage=0;
    if(direction=='previous'){
        set_position--;
        if(set_position<0)set_position=$(pp_images).size()-1;
    }else if(direction=='next'){
        set_position++;
        if(set_position>$(pp_images).size()-1)set_position=0;
    }else{
        set_position=direction;
    };

    rel_index=set_position;
    if(!doresize)doresize=true;
    $('.pp_contract').removeClass('pp_contract').addClass('pp_expand');
    _hideContent(function(){
        $.prettyPhoto.open();
    });
};

$.prettyPhoto.changeGalleryPage=function(direction){
    if(direction=='next'){
        currentGalleryPage++;
        if(currentGalleryPage>totalPage)currentGalleryPage=0;
    }else if(direction=='previous'){
        currentGalleryPage--;
        if(currentGalleryPage<0)currentGalleryPage=totalPage;
    }else{
        currentGalleryPage=direction;
    };

    slide_speed=(direction=='next'||direction=='previous')?settings.animation_speed:0;
    slide_to=currentGalleryPage*(itemsPerPage*itemWidth);
    $pp_gallery.find('ul').animate({
        left:-slide_to
        },slide_speed);
};

$.prettyPhoto.startSlideshow=function(){
    if(typeof pp_slideshow=='undefined'){
        $pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function(){
            $.prettyPhoto.stopSlideshow();
            return false;
        });
        pp_slideshow=setInterval($.prettyPhoto.startSlideshow,settings.slideshow);
    }else{
        $.prettyPhoto.changePage('next');
    };

}
$.prettyPhoto.stopSlideshow=function(){
    $pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function(){
        $.prettyPhoto.startSlideshow();
        return false;
    });
    clearInterval(pp_slideshow);
    pp_slideshow=undefined;
}
$.prettyPhoto.close=function(){
    if($pp_overlay.is(":animated"))return;
    $.prettyPhoto.stopSlideshow();
    $pp_pic_holder.stop().find('object,embed').css('visibility','hidden');
    $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){
        $(this).remove();
    });
    $pp_overlay.fadeOut(settings.animation_speed,function(){
        if($.browser.msie&&$.browser.version==6)$('select').css('visibility','visible');
        if(settings.hideflash)$('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','visible');
        $(this).remove();
        $(window).unbind('scroll.prettyphoto');
        settings.callback();
        doresize=true;
        pp_open=false;
        delete settings;
    });
};

function _showContent(){
    $('.pp_loaderIcon').hide();
    projectedTop=scroll_pos['scrollTop']+((windowHeight/2)-(pp_dimensions['containerHeight']/2));
    if(projectedTop<0)projectedTop=0;
    $ppt.fadeTo(settings.animation_speed,1);
    $pp_pic_holder.find('.pp_content').animate({
        height:pp_dimensions['contentHeight'],
        width:pp_dimensions['contentWidth']
        },settings.animation_speed);
    $pp_pic_holder.animate({
        'top':projectedTop,
        'left':(windowWidth/2)-(pp_dimensions['containerWidth']/2),
        width:pp_dimensions['containerWidth']
        },settings.animation_speed,function(){
        $pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(pp_dimensions['height']).width(pp_dimensions['width']);
        $pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed);
        if(isSet&&_getFileType(pp_images[set_position])=="image"){
            $pp_pic_holder.find('.pp_hoverContainer').show();
        }else{
            $pp_pic_holder.find('.pp_hoverContainer').hide();
        }
        if(pp_dimensions['resized']){
            $('a.pp_expand,a.pp_contract').show();
        }else{
            $('a.pp_expand').hide();
        }
        if(settings.autoplay_slideshow&&!pp_slideshow&&!pp_open)$.prettyPhoto.startSlideshow();
        if(settings.deeplinking)
            setHashtag();
        settings.changepicturecallback();
        pp_open=true;
    });
    _insert_gallery();
};

function _hideContent(callback){
    $pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
    $pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed,function(){
        $('.pp_loaderIcon').show();
        callback();
    });
};

function _checkPosition(setCount){
    (setCount>1)?$('.pp_nav').show():$('.pp_nav').hide();
};

function _fitToViewport(width,height){
    resized=false;
    _getDimensions(width,height);
    imageWidth=width,imageHeight=height;
    if(((pp_containerWidth>windowWidth)||(pp_containerHeight>windowHeight))&&doresize&&settings.allow_resize&&!percentBased){
        resized=true,fitting=false;
        while(!fitting){
            if((pp_containerWidth>windowWidth)){
                imageWidth=(windowWidth-200);
                imageHeight=(height/width)*imageWidth;
            }else if((pp_containerHeight>windowHeight)){
                imageHeight=(windowHeight-200);
                imageWidth=(width/height)*imageHeight;
            }else{
                fitting=true;
            };

            pp_containerHeight=imageHeight,pp_containerWidth=imageWidth;
        };

        _getDimensions(imageWidth,imageHeight);
        if((pp_containerWidth>windowWidth)||(pp_containerHeight>windowHeight)){
            _fitToViewport(pp_containerWidth,pp_containerHeight)
            };

};

return{
    width:Math.floor(imageWidth),
    height:Math.floor(imageHeight),
    containerHeight:Math.floor(pp_containerHeight),
    containerWidth:Math.floor(pp_containerWidth)+(settings.horizontal_padding*2),
    contentHeight:Math.floor(pp_contentHeight),
    contentWidth:Math.floor(pp_contentWidth),
    resized:resized
};

};

function _getDimensions(width,height){
    width=parseFloat(width);
    height=parseFloat(height);
    $pp_details=$pp_pic_holder.find('.pp_details');
    $pp_details.width(width);
    detailsHeight=parseFloat($pp_details.css('marginTop'))+parseFloat($pp_details.css('marginBottom'));
    $pp_details=$pp_details.clone().addClass(settings.theme).width(width).appendTo($('body')).css({
        'position':'absolute',
        'top':-10000
    });
    detailsHeight+=$pp_details.height();
    detailsHeight=(detailsHeight<=34)?36:detailsHeight;
    if($.browser.msie&&$.browser.version==7)detailsHeight+=8;
    $pp_details.remove();
    $pp_title=$pp_pic_holder.find('.ppt');
    $pp_title.width(width);
    titleHeight=parseFloat($pp_title.css('marginTop'))+parseFloat($pp_title.css('marginBottom'));
    $pp_title=$pp_title.clone().appendTo($('body')).css({
        'position':'absolute',
        'top':-10000
    });
    titleHeight+=$pp_title.height();
    $pp_title.remove();
    pp_contentHeight=height+detailsHeight;
    pp_contentWidth=width;
    pp_containerHeight=pp_contentHeight+titleHeight+$pp_pic_holder.find('.pp_top').height()+$pp_pic_holder.find('.pp_bottom').height();
    pp_containerWidth=width;
}
function _getFileType(itemSrc){
    if(itemSrc.match(/youtube\.com\/watch/i)){
        return'youtube';
    }else if(itemSrc.match(/vimeo\.com/i)){
        return'vimeo';
    }else if(itemSrc.match(/\b.mov\b/i)){
        return'quicktime';
    }else if(itemSrc.match(/\b.swf\b/i)){
        return'flash';
    }else if(itemSrc.match(/\biframe=true\b/i)){
        return'iframe';
    }else if(itemSrc.match(/\bajax=true\b/i)){
        return'ajax';
    }else if(itemSrc.match(/\bcustom=true\b/i)){
        return'custom';
    }else if(itemSrc.substr(0,1)=='#'){
        return'inline';
    }else{
        return'image';
    };

};

function _center_overlay(){
    if(doresize&&typeof $pp_pic_holder!='undefined'){
        scroll_pos=_get_scroll();
        contentHeight=$pp_pic_holder.height(),contentwidth=$pp_pic_holder.width();
        projectedTop=(windowHeight/2)+scroll_pos['scrollTop']-(contentHeight/2);
        if(projectedTop<0)projectedTop=0;
        if(contentHeight>windowHeight)
            return;
        $pp_pic_holder.css({
            'top':projectedTop,
            'left':(windowWidth/2)+scroll_pos['scrollLeft']-(contentwidth/2)
            });
    };

};

function _get_scroll(){
    if(self.pageYOffset){
        return{
            scrollTop:self.pageYOffset,
            scrollLeft:self.pageXOffset
            };

}else if(document.documentElement&&document.documentElement.scrollTop){
    return{
        scrollTop:document.documentElement.scrollTop,
        scrollLeft:document.documentElement.scrollLeft
        };

}else if(document.body){
    return{
        scrollTop:document.body.scrollTop,
        scrollLeft:document.body.scrollLeft
        };

};

};

function _resize_overlay(){
    windowHeight=$(window).height(),windowWidth=$(window).width();
    if(typeof $pp_overlay!="undefined")$pp_overlay.height($(document).height()).width(windowWidth);
};

function _insert_gallery(){
    if(isSet&&settings.overlay_gallery&&_getFileType(pp_images[set_position])=="image"&&(settings.ie6_fallback&&!($.browser.msie&&parseInt($.browser.version)==6))){
        itemWidth=52+5;
        navWidth=(settings.theme=="facebook"||settings.theme=="pp_default")?50:30;
        itemsPerPage=Math.floor((pp_dimensions['containerWidth']-100-navWidth)/itemWidth);
        itemsPerPage=(itemsPerPage<pp_images.length)?itemsPerPage:pp_images.length;
        totalPage=Math.ceil(pp_images.length/itemsPerPage)-1;
        if(totalPage==0){
            navWidth=0;
            $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').hide();
        }else{
            $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').show();
        };

        galleryWidth=itemsPerPage*itemWidth;
        fullGalleryWidth=pp_images.length*itemWidth;
        $pp_gallery.css('margin-left',-((galleryWidth/2)+(navWidth/2))).find('div:first').width(galleryWidth+5).find('ul').width(fullGalleryWidth).find('li.selected').removeClass('selected');
        goToPage=(Math.floor(set_position/itemsPerPage)<totalPage)?Math.floor(set_position/itemsPerPage):totalPage;
        $.prettyPhoto.changeGalleryPage(goToPage);
        $pp_gallery_li.filter(':eq('+set_position+')').addClass('selected');
    }else{
        $pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave');
    }
}
function _build_overlay(caller){
    settings.markup=settings.markup.replace('{pp_social}',(settings.social_tools)?settings.social_tools:'');
    $('body').append(settings.markup);
    $pp_pic_holder=$('.pp_pic_holder'),$ppt=$('.ppt'),$pp_overlay=$('div.pp_overlay');
    if(isSet&&settings.overlay_gallery){
        currentGalleryPage=0;
        toInject="";
        for(var i=0;i<pp_images.length;i++){
            if(!pp_images[i].match(/\b(jpg|jpeg|png|gif)\b/gi)){
                classname='default';
                img_src='';
            }else{
                classname='';
                img_src=pp_images[i];
            }
            toInject+="<li class='"+classname+"'><a href='#'><img src='"+img_src+"' width='50' alt='' /></a></li>";
        };

        toInject=settings.gallery_markup.replace(/{gallery}/g,toInject);
        $pp_pic_holder.find('#pp_full_res').after(toInject);
        $pp_gallery=$('.pp_pic_holder .pp_gallery'),$pp_gallery_li=$pp_gallery.find('li');
        $pp_gallery.find('.pp_arrow_next').click(function(){
            $.prettyPhoto.changeGalleryPage('next');
            $.prettyPhoto.stopSlideshow();
            return false;
        });
        $pp_gallery.find('.pp_arrow_previous').click(function(){
            $.prettyPhoto.changeGalleryPage('previous');
            $.prettyPhoto.stopSlideshow();
            return false;
        });
        $pp_pic_holder.find('.pp_content').hover(function(){
            $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn();
        },function(){
            $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut();
        });
        itemWidth=52+5;
        $pp_gallery_li.each(function(i){
            $(this).find('a').click(function(){
                $.prettyPhoto.changePage(i);
                $.prettyPhoto.stopSlideshow();
                return false;
            });
        });
    };

    if(settings.slideshow){
        $pp_pic_holder.find('.pp_nav').prepend('<a href="#" class="pp_play">Play</a>')
        $pp_pic_holder.find('.pp_nav .pp_play').click(function(){
            $.prettyPhoto.startSlideshow();
            return false;
        });
    }
    $pp_pic_holder.attr('class','pp_pic_holder '+settings.theme);
    $pp_overlay.css({
        'opacity':0,
        'height':$(document).height(),
        'width':$(window).width()
        }).bind('click',function(){
        if(!settings.modal)$.prettyPhoto.close();
    });
    $('a.pp_close').bind('click',function(){
        $.prettyPhoto.close();
        return false;
    });
    $('a.pp_expand').bind('click',function(e){
        if($(this).hasClass('pp_expand')){
            $(this).removeClass('pp_expand').addClass('pp_contract');
            doresize=false;
        }else{
            $(this).removeClass('pp_contract').addClass('pp_expand');
            doresize=true;
        };

        _hideContent(function(){
            $.prettyPhoto.open();
        });
        return false;
    });
    $pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click',function(){
        $.prettyPhoto.changePage('previous');
        $.prettyPhoto.stopSlideshow();
        return false;
    });
    $pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click',function(){
        $.prettyPhoto.changePage('next');
        $.prettyPhoto.stopSlideshow();
        return false;
    });
    _center_overlay();
};

if(!pp_alreadyInitialized&&getHashtag()){
    pp_alreadyInitialized=true;
    hashIndex=getHashtag();
    hashRel=hashIndex;
    hashIndex=hashIndex.substring(hashIndex.indexOf('/')+1,hashIndex.length-1);
    hashRel=hashRel.substring(0,hashRel.indexOf('/'));
    setTimeout(function(){
        $("a[rel^='"+hashRel+"']:eq("+hashIndex+")").trigger('click');
    },50);
}
return this.unbind('click.prettyphoto').bind('click.prettyphoto',$.prettyPhoto.initialize);
};

function getHashtag(){
    url=location.href;
    hashtag=(url.indexOf('#!')!=-1)?decodeURI(url.substring(url.indexOf('#!')+2,url.length)):false;
    return hashtag;
};

function setHashtag(){
    if(typeof theRel=='undefined')return;
    location.hash='!'+theRel+'/'+rel_index+'/';
};

function getParam(name,url){
    name=name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS="[\\?&]"+name+"=([^&#]*)";
    var regex=new RegExp(regexS);
    var results=regex.exec(url);
    return(results==null)?"":results[1];
}
})(jQuery);
var pp_alreadyInitialized=false;

