/* 
    Document   : SceneRotate.js
    Created on : 27-May-2011, 2:27:05 PM
    Author     : David Pan <David.Pan@manwin.com>
    Version    : $Id
    Description:
        
 */

(function($){
    
    // Set the plugin namespace
    if(!$.mwplugin){
        $.mwplugin = new Object();
    };
    
    $.mwplugin.sceneRotate = function(el, options){
    
        var base = this;
        var urlBeg = '';
        var urlEnd = '';
        var imgHeight = '';
        var imgWidth = '';
        var curImgObj = '';
        var imgInterval = '';
        var curImgNb = 1;
        var nextImgNb = 2;
        var imgPath = '';
        var imgIntval = '';
        var imgTempSwap = '';
        var imgCurSwap ='';
        var imgSwapStatus = true;
        var nbImg = null;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Add a reverse reference to the DOM object
        base.$el.data("mwplugin.sceneRotate", base);
        
        // Init the plugin
        base.init = function(){
            base.options = $.extend({},$.mwplugin.sceneRotate.defaultOptions, options);
            base.loadImg();
        };
        
        base.loadImg = function(){
            if (typeof(base.options.domPath) === "undefined") base.options.domPath = '';
            else base.options.domPath+= ' ';
            $(base.el,base.options.domPath).hover(function(){
                curImgObj = this;
                imgInterval = setInterval(function() {
                    base.swapImage(curImgObj);
                }, base.options.speed);
            }, function() {
                clearInterval(imgInterval);
                base.changeImg(false);
                curImgObj = null;
                // save url information for find it quicker later
                base.saveImgInfo(this);
            });
        };
        
        base.swapImage = function(id) {
            
            if (typeof (id) === 'object') {
                 imgCurSwap = $(id);
            }else{
                imgCurSwap = id;
            }
            
            var duration = parseInt(imgCurSwap.data(base.options.dataDurationName));
            
            if(typeof (duration) == 'undefined' || duration == null || duration == '' || isNaN(duration)) {
                if(base.options.logs != 0) {
                    console.log("data duration var not set");
                }
                base.destroy();
                return false;
            }
            // Init image size
            if(imgWidth == '') {
                imgWidth = base.options.imgWidth;
            }           
            if(imgHeight == '') {
                imgHeight = base.options.imgHeight;
            }

            if (duration > 0 && nbImg == null) {
                
                if(base.options.imgDurInterVal > 0) {duration /= base.options.imgDurInterVal;}
                // if the img interval wasn't set
                if(base.options.imgInterval == 0) { 
                    imgIntval = Math.floor(duration / base.options.nbImg); //Get the interval between each image in case the NumberMax image is set
                } else {
                    nbImg = Math.floor(duration / base.options.imgInterval); // Get the number total of images the plugin must go throught
                    imgIntval = base.options.imgInterval;
                }
            } 

            // get the image path using regex
            if(urlBeg == '') {
                base.getImgPathWithRegex(imgCurSwap);
            }
           
            if (curImgNb != 0) {
                nextImgNb = parseInt(curImgNb,10) + imgIntval;
            }
            
            if(nextImgNb > (nbImg*imgIntval)) {
                // Stop here
                nextImgNb = 1;
                imgSwapStatus = true;
            }
            
            // add zero padding to the img name
            nextImgNb = base.zeroPad(nextImgNb, 4);
            
            // Load the image in a temp var
            imgTempSwap = new Image();
            imgTempSwap.onerror = function(){
                if(base.options.errorStop) {
                    // Stop the plugin
                    base.destroy();
                } else {
                    // Try set the max img number to this last images
                    if(base.options.logs != 0) console.log(imgTempSwap.src);
                    nbImg = curImgNb/imgIntval;
                    nextImgNb = 1;
                }
            };
            
            imgTempSwap.onload = function(){
                base.changeImg(imgSwapStatus);
            }

            imgTempSwap.src = base.getImgPath();
            
        };
        
        
        base.changeImg = function(status) {

            var newsrc = '';
            if (status==false) {
                if(typeof(urlBeg) == 'undefined' || urlBeg == "") {
                    newsrc = imgCurSwap.attr("src");
                }else{
                    newsrc = urlBeg + urlEnd;
                }
            } else {
                newsrc = imgTempSwap.src;
            }
            
            if (imgCurSwap.attr('src') != newsrc) {
                curImgNb = nextImgNb;
                imgCurSwap.attr('src', newsrc);
            }

        };
        
        base.getImgPathWithRegex = function(imgCurSwap){
              
            if (typeof(imgCurSwap.data("url_beg")) == "undefined") {
                // Use a regex to automatically get url path
                var re = new RegExp(base.options.regex, "i");
                var regs = imgCurSwap.attr("src").match(re);
                if(base.options.logs) console.log(regs);
                
                if(regs != null) {
                    if(typeof(regs[1]) != "undefined" ) urlBeg = regs[1];
                    if(typeof(regs[2]) != "undefined" ) urlEnd = regs[2];
                    if(typeof(regs[3]) != "undefined" ) imgHeight = regs[3];
                    if(typeof(regs[4]) != "undefined" ) imgWidth = regs[4];
                }
            } else {
                // Not needed cause we are in an object
                base.loadImgInfo(imgCurSwap);
            }
        };
        
        base.getImgPath = function() {
            var imgNewSrc = '';
            
            if(imgPath == '') {
                if(base.options.path != '') {
                    imgNewSrc += base.options.path;
                } else {
                    imgNewSrc += urlBeg;
                }

                if(base.options.pathBeforeImgFolder != '') {
                    imgNewSrc += '/'+base.options.pathBeforeImgFolder;
                }

                if(base.options.imgFolder != '') {
                    imgNewSrc += '/'+base.options.imgFolder;
                }

                if(base.options.useWidthInFolderName) {
                    if(base.options.imgFolder == '') imgNewSrc += '/';
                    imgNewSrc += imgWidth;
                }

                if(base.options.useHeightInFolderName) {
                    if(base.options.useWidthInFolderName) { 
                        imgNewSrc += 'x';
                    } else {
                        if(base.options.imgFolder != '') imgNewSrc += '/';
                    }

                    imgNewSrc += imgHeight;
                }

                if(base.options.imgPrefix != '') {
                    imgNewSrc += '/'+base.options.imgPrefix;
                }else{
                    imgNewSrc += '/';
                }
            } else {
                imgNewSrc = imgPath;
            }
            
            imgNewSrc += nextImgNb+base.options.imgExt;
            
            return imgNewSrc;
        }
        
        // Not necessary since we use object unless we destroy the object
        base.loadImgInfo = function(imgObj) {
            urlEnd = imgObj.data("urlBeg");
            urlBeg = imgObj.data("urlEnd");
            imgHeight = imgObj.data("imgHeight");
            imgWidth = imgObj.data("imgWidth");
            curImgNb = parseInt(imgObj.data("curImgNb"),10);
            nextImgNb = parseInt(imgObj.data("nextImgNb"),10);
        };
        
         // Not necessary since we use object unless we destroy the object
        base.saveImgInfo = function(imgObj) {
            if(urlBeg != '') {
                imgObj.data("urlBeg", urlEnd);
                imgObj.data("urlEnd", urlBeg);
                imgObj.data("imgHeight", imgHeight);
                imgObj.data("imgWidth", imgWidth);
                imgObj.data("curImgNb", curImgNb);
                imgObj.data("nextImgNb", nextImgNb);
                
                return true;
            } else {
                return false;
            }
        };
        
        base.zeroPad = function(input,count){
            
            var paddedNum = '' + input; // Parse to string to keep the leading zero
            
            while(paddedNum.length < count) {
                paddedNum = '0'+paddedNum;
            }
            return paddedNum;
        };
        
        base.destroy = function() {
            // Stop the plugin
            base.changeImg(false);
            clearInterval(imgInterval);
            $(curImgObj).unbind('mouseenter mouseleave');
            curImgObj = null;
        }
        
        // Make it go
        base.init();
        
    };
    
    // this are the default options
    $.mwplugin.sceneRotate.defaultOptions = {
        //        animation	: 'fade',
        speed		: 500,
//        image : '.swap-image',
        domPath : '',
        dataDurationName : 'duration', // Name of the data where duration is set
        nbImg : 42, // Number of images you want
        imgInterval: 40, // Interval between each images (the number of images the plugin must jump) set to 0 if you to use the nbImage parameter
        imgDurInterVal : 3, // Interval between each screen shot of image (in case of the duration not egal to the total number of image available)
        path : '', //Use another path
        pathBeforeImgFolder : 'caps', // Path to add before Img Folder
        imgPrefix : '', // Use another img Prefix
        useWidthInFolderName : 0,// Add width in folder Name
        useHeightInFolderName : 0, // Add height in folder Name
        imgFolder :'thm', //Img Folder Name or prefix
        regex : '(.*/scene/[0-9]/[0-9]/[0-9]+)(/.*/([0-9]+)x([0-9]+).*)', // First catch = url begin, 2nd url end, 3rd img width, 4th img height
        imgExt : '.jpg', // Img extension
        imgWidth : 224, // Img default width 
        imgHeight : 126, // Img default height
        logs : 0, // Activate console logs
        errorStop : 0 // Stop the plugin if an error happen
    };
    
    $.fn.sceneRotate = function(options){
        return this.each(function(){
            (new $.mwplugin.sceneRotate(this, options));
        });
    };
    
})(jQuery);
