/* jLightBox (using jQuery library).
*--------------------------------------------*
*  @author : ukhome ( ukhome@gmail.com | ntkhoa_friends@yahoo.com )
*--------------------------------------------*
*  @released : 24-Mar-2009 : version 1.0
*--------------------------------------------*
*  @revision history : ( latest version : 1.0 )
*--------------------------------------------*
*      + 24-Mar-2009 : version 1.0
*          - released
*--------------------------------------------*
*/

/* package $lightbox.ImageControl
*/

/*
* parent = $lightbox object
*/

$lightbox.ImageControl = function (parent, options/*optional: use in case call by external interface*/) {
    //Fields
    this.parent = parent;
    var self = this;
    var img = new Image();
    var imgSource = typeof( options ) != "undefined" && typeof( options.href ) != "undefined" ? options.href : parent.handler.attr("href");
    var obj = jQuery(img);

	//Methods
    this.ajustPopupSize = function ( obj, imgSource, useDefaultValue ) {  // ajust popup size to adapt image size
        //reset
        obj.unbind("load", scale);
        obj.unbind("error", handleErrorException);

        if ( useDefaultValue ) {
            var width = height = "100px";
        }
        else {
            var width = parent.popup.outerWidth();
            var height = parent.popup.outerHeight();
        }
        parent.popup.css({
            width: width,
            height: height,
            padding: "0",
            overflow: "hidden"
        });
        parent.popup.children().hide();
        parent.popup.show().center();
		
        var scale = function () {
            clearTimeout(loadingTimeOut);
            /*scale image to fit window in case image too big*/
            /*if ( obj.width() >= jQuery(window).width() && obj.height() >= jQuery(window).height() ) {
                var k1 = jQuery(window).width()*0.85/obj.width();
                var k2 = jQuery(window).height()*0.85/obj.height();
                var k = k1 > k2
                            ? Math.round(Math.pow(10, 4)*k2)/Math.pow(10, 4)
                            : Math.round(Math.pow(10, 4)*k1)/Math.pow(10, 4);

                var ajustedWidth = obj.width()*k;
                var ajustedHeight = obj.height()*k;
                obj.attr("width", ajustedWidth);
                obj.attr("height", ajustedHeight);
            }
            else if ( obj.width() >= jQuery(window).width() && obj.height() < jQuery(window).height() ) {
                //scale depend width
                var ajustedWidth = jQuery(window).width()*0.85;
                var ajustedHeight = ajustedWidth*obj.height()/obj.width();
                obj.attr("width", ajustedWidth);
                obj.attr("height", ajustedHeight);
            }
            else if ( obj.width() < jQuery(window).width() && obj.height() >= jQuery(window).height() ) {
                //scale depend height
                var ajustedHeight = jQuery(window).height()*0.85;
                var ajustedWidth = ajustedHeight*obj.width()/obj.height();
                obj.attr("width", ajustedWidth);
                obj.attr("height", ajustedHeight);
            }
            parent.popup.removeClass("LightBoxPopupLoading");
            parent.popup.find("p.LoadingErrorAler").remove();
            parent.popup.scale({
                width: obj.width(),
                height: obj.height(),
                padding: "0px 0px 0px 0px",
                sync: false
            }, 500, "swing", function () {
                //callback
                parent.popup.children("img").fadeIn("normal");
                parent.popup.children("*:not(img)").show();
            });*/
			
			/*********modify************/
			//alert(obj.outerWidth(true));			
			
			if ( obj.outerWidth(true) >= jQuery(window).width() && obj.outerHeight(true) >= jQuery(window).height() ) {
                var k1 = jQuery(window).width()*0.85/obj.outerWidth(true);
                var k2 = jQuery(window).height()*0.85/obj.outerHeight(true);
                var k = k1 > k2
                            ? Math.round(Math.pow(10, 4)*k2)/Math.pow(10, 4)
                            : Math.round(Math.pow(10, 4)*k1)/Math.pow(10, 4);

                var ajustedWidth = obj.outerWidth(true)*k;
                var ajustedHeight = obj.outerHeight(true)*k;
                obj.attr("width", ajustedWidth);
                obj.attr("height", ajustedHeight);
            }
            else if ( obj.outerWidth(true) >= jQuery(window).width() && obj.outerHeight(true) < jQuery(window).height() ) {
                //scale depend width
                var ajustedWidth = jQuery(window).width()*0.85;
                var ajustedHeight = ajustedWidth*obj.outerHeight(true)/obj.outerWidth(true);
                obj.attr("width", ajustedWidth);
                obj.attr("height", ajustedHeight);
            }
            else if ( obj.outerWidth(true) < jQuery(window).width() && obj.outerHeight(true) >= jQuery(window).height() ) {
                //scale depend height
                var ajustedHeight = jQuery(window).height()*0.85;
                var ajustedWidth = ajustedHeight*obj.outerWidth(true)/obj.outerHeight(true);
                obj.attr("width", ajustedWidth);
                obj.attr("height", ajustedHeight);
            }			
            parent.popup.removeClass("LightBoxPopupLoading");
            parent.popup.find("p.LoadingErrorAler").remove();
            parent.popup.scale({
                width: obj.outerWidth(true) + 6,
                height: obj.outerHeight(true) +14,
                padding: "0px 0px 0px 0px",
                sync: false
            }, -100, "swing", function () {
                //callback
                //parent.popup.children("img").fadeIn("normal");
				parent.popup.find("img").fadeIn("normal");
				obj.before("<div class=\"LightBoxPopupTop FixPng\"></div>");
				obj.wrap("<div class=\"LightBoxPopupRight FixPng\"><div class=\"LightBoxPopupBottom FixPng\"><div class=\"LightBoxPopupInner\" id=\"lightBoxPopupInner\"></div></div></div>");
				parent.popup.addClass("BgNone");
                parent.popup.children("*:not(img)").show();
            });
			
        }

        var handleErrorException = function (/*arguments[0]: err*/) {
            if ( arguments[0].constructor == String ) {
                var errorMsg = arguments[0];
            }
            else {
                var errorMsg = "Can not find image !";
            }
            clearTimeout(loadingTimeOut);
            parent.popup.removeClass("LightBoxPopupLoading");
            parent.popup.find("p.LoadingErrorAler").remove();
            parent.popup.scale({
                width: "500px",
                height: "300px",
                padding: "0px 0px 0px 0px",
                sync: true
            }, "normal", "swing", function () {
                //callback
                parent.popup.children("*:not(img)").show();
                parent.popup.prepend("<p class=\"LoadingErrorAler\" style=\"width: 100%; height: 300px;\">" + errorMsg +"</p>");
            });
        }

        //binding events on img obj
        obj.bind("load", scale);
        obj.bind("error", handleErrorException);
        var loadingTimeOut = setTimeout(function () {
            obj.unbind("load", scale);
            obj.unbind("error", handleErrorException);
            handleErrorException("Respone take too long...");
        }, 20000);
        obj.attr("src", imgSource );

        return parent;
    }

    //Constructor
    parent.popup.addClass("LightBoxPopupLoading");
    img.title = typeof( options ) != "undefined" && typeof( options.title ) != "undefined" ? options.title : parent.handler.find("img:first").attr("title");
    parent.popupContent.remove(); //no need popupContent wrapper	
    obj.appendTo( parent.popup );	
	//obj.appendTo( parent.innerPopup );
    if ( jQuery(parent.options.internalContent).attr("class") != "" ) {
        var groupImages = jQuery( "." + jQuery(parent.options.internalContent).attr("class") );
        if ( groupImages.length > 1 ) {
            var index;
            for ( var i = 0 ; i < groupImages.length ; i++ ) {
                if ( groupImages.eq(i).attr("id") == jQuery(parent.options.internalContent).attr("id") ) {
                    index = i;
                    break;
                }
            }
            parent.nextBtn = jQuery("<a href=\"#\" title=\"next\" class=\"NextBtn\">next</a>");
            parent.prevBtn = jQuery("<a href=\"#\" title=\"prev\" class=\"PrevBtn\">prev</a>");
            parent.popup
                .append( "<div class=\"ControlBar\"><p class=\"Index\">Image <span>" + (index+1) +"</span> of <span>" + groupImages.length  + "</span></p></div>");
            parent.popup.find("div.ControlBar:first")
                .append(parent.nextBtn)
                .append(parent.prevBtn );

            parent.nextBtn.bind("click", function () {
                obj.removeAttr("width");
                obj.removeAttr("height");
                parent.popup.addClass("LightBoxPopupLoading");
                if ( index < groupImages.length-1 ) {
                    index++;
                }
                else {
                    index = 0;
                }
                imgSource = groupImages.eq(index).parent("a").attr("href");
                obj.attr("title", groupImages.eq(index).parent("a").find("img:first").attr("title") );
                parent.popup.find("p.Index > span:first").text(index+1);
                parent.popup.find("p.CaptionGallery:first").text(obj.attr("title"));
                self.ajustPopupSize( obj, imgSource, false ); //show image
                return false;
            });

            parent.prevBtn.bind("click", function () {
                obj.removeAttr("width");
                obj.removeAttr("height");
                parent.popup.addClass("LightBoxPopupLoading");
                if ( index > 0 ) {
                    index--;
                }
                else {
                    index = groupImages.length-1;
                }
                imgSource = groupImages.eq(index).parent("a").attr("href");
                obj.attr("title", groupImages.eq(index).parent("a").find("img:first").attr("title") );
                parent.popup.find("p.Index > span:first").text(index+1);
                parent.popup.find("p.CaptionGallery:first").text(obj.attr("title"));
                self.ajustPopupSize( obj, imgSource, false ); //show image
                return false;
            });
        }
    }
    if ( typeof( obj.attr("title") ) != "undefined" && obj.attr("title") != "" ) {
        if ( parent.popup.find("div.ControlBar").length == 0 ) {
            parent.popup.append("<div class=\"ControlBar\"></div>");
            parent.popup.find("div.ControlBar").append( jQuery("<p class=\"Caption\">" + obj.attr("title") + "</p>") );
            if ( parent.options.closeBtn != null ) {
                parent.popup.find("div.ControlBar").append( parent.options.closeBtn.removeClass("CloseBtn").addClass("CloseImageBtn") );
            }
        }
        else {
            parent.popup.find("div.ControlBar > p.Index:first").before( jQuery("<p class=\"CaptionGallery\">" + obj.attr("title") + "</p>") );
            if ( parent.options.closeBtn != null ) {
                parent.popup.find("a.NextBtn:first").before( parent.options.closeBtn.removeClass("CloseBtn").addClass("CloseGalleryImageBtn") );
            }
        }
    }
    else if ( parent.options.closeBtn != null ) {
        if ( parent.popup.find("div.ControlBar").length == 0 ) {
            parent.popup.append("<div class=\"ControlBar\"></div>");
            parent.popup.find("div.ControlBar").append( parent.options.closeBtn.removeClass("CloseBtn").addClass("CloseImageBtn") );
        }
        else {
            parent.popup.find("a.NextBtn:first").before( parent.options.closeBtn.removeClass("CloseBtn").addClass("CloseGalleryImageBtn") );
        }
    }

    parent.overlays.show();
    this.ajustPopupSize( obj, imgSource, true ); //show image
    //end. Constructor

}

