/**
 * Custom Functions for Excellence Top Image
 */
ER.app.page.topImg.width = 920;
ER.app.page.topImg.gap = 0;
ER.app.page.topImg.qty = 0;
ER.app.page.topImg.ind = 1;
ER.app.page.topImg.slideNo = 1;
ER.app.page.topImg.getMargin = false;
ER.app.page.topImg.btnSize = {w:43,h:81};

ER.app.page.topImg.ini = function() {
    $('.igallery')['iGallery']();
    if ($.browser.safari) iPhoneUI.initTouchEvents("igalleryWrap");
    ER.app.page.topImg.setUp();
}

ER.app.page.topImg.setMargin = function(ifrm, marginLeft) {
    ER.app.page.topImg.getMargin = true;
    ifrm.stop(true,true);
    ifrm.animate({'marginLeft':marginLeft});
}
    
ER.app.page.topImg.setUp = function(n) {
    if ($("#ctrlTopImg .topImgBullet").length > 1) {
        $(".galleryui .frame").css({"cursor":"move"});

        $("#prevTopImg div").hover(
            function() { $(this).css({"background-position":"0px -"+ER.app.page.topImg.btnSize.h+"px"}) },
            function() { $(this).css({"background-position":"0px 0px"}) }
        );
        $("#nextTopImg div").hover(
            function() { $(this).css({"background-position":"-"+ER.app.page.topImg.btnSize.w+"px -"+ER.app.page.topImg.btnSize.h+"px"}) },
            function() { $(this).css({"background-position":"-"+ER.app.page.topImg.btnSize.w+"px 0px"}) }
        );
        $("#galleryWrapper, #ctrlTopImg").hover(
            function() { $("#ctrlTopImg").find(".arrow").show() },
            function() { $("#ctrlTopImg").find(".arrow").hide() }
        );
        $("#ctrlTopImg .topImgBullet").hover(
            function() { if (!$(this).hasClass("on")) $(this).addClass("hover") },
            function() { $(this).removeClass("hover") }
        );
        $("#ctrlTopImg .topImgBullet").click(function () { 
            ER.app.page.topImg.autoScroll(parseInt($(this).attr("id").replace("topImgBullet_",""),10))
        });

        $("#prevTopImg .arrow").click(function () { ER.app.page.topImg.jump(-1) });
        $("#nextTopImg .arrow").click(function () { ER.app.page.topImg.jump(1) });

        ER.app.page.topImg.highLight(1);
    }
}

ER.app.page.topImg.highLight = function(slideNo) {
    $("#ctrlTopImg .topImgBullet").removeClass("off").removeClass("on").addClass("off");;
    $("#topImgBullet_"+slideNo).removeClass("off").addClass("on");
    ER.app.page.topImg.slideNo = slideNo;
}

ER.app.page.topImg.current = function() {
    var ifrm = $("#igalleryWrap .frame")
        current = (((parseInt(ifrm.css("marginLeft").replace("px",""),10)*-1)-ER.app.page.topImg.gap)/(ER.app.page.topImg.width+ER.app.page.topImg.gap))+1;
    return current;
}

ER.app.page.topImg.autoScroll = function(slideNo) {
    if (ER.app.page.topImg.slideNo != slideNo) {
        var ifrm = $("#igalleryWrap .frame"),
            current = ER.app.page.topImg.current(),
            marginLeft = (((slideNo-1)*(ER.app.page.topImg.width+ER.app.page.topImg.gap))+ER.app.page.topImg.gap)*-1;

        ER.app.page.topImg.getMargin = true;
        ifrm.stop(true,true);

        ifrm.animate({'marginLeft':marginLeft}, 1000*Math.abs(current-slideNo));
        ER.app.page.topImg.highLight(slideNo);
    }
}

ER.app.page.topImg.jump = function(No) {
    var tmp = ER.app.page.topImg.slideNo + No;
    if (tmp <= 0) tmp = ER.app.page.topImg.qty;
    if (tmp > ER.app.page.topImg.qty) tmp = 1;
    ER.app.page.topImg.autoScroll(tmp);
}


/**
 * jQuery iPhone UI Library
 * http://iphone.hohli.com/
 *
 * Copyright 2010, Anton Shevchuk
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://docs.jquery.com/License
 *
 * @version 0.1
 * 
 * ADAPTED FOR chelseastar BY 
 * Juan F. Sarria
 * 
 */
iPhoneUI = {
    on:false,
	initTouchEvents:function(sID) {
        var doc = document.getElementById(sID);
		doc.addEventListener("touchstart",  iPhoneUI.touchHandler, true);
	    doc.addEventListener("touchmove",   iPhoneUI.touchHandler, true);
	    doc.addEventListener("touchend",    iPhoneUI.touchHandler, true);
	    doc.addEventListener("touchcancel", iPhoneUI.touchHandler, true); 
	},
	/**
	 * Touch events handler
	 */
	touchHandler:function(event) {
	    var touches = event.changedTouches,
	        first = touches[0],
	        type = "";
    
	    switch(event.type) {
	        case "touchstart": type = "mousedown"; iPhoneUI.on=true; break;
	        case "touchmove":  type = "mousemove"; iPhoneUI.on=true; break;        
	        case "touchend":   type = "mouseup";   iPhoneUI.on=false; break;
	        default: return;
	    }
	        
	    //initMouseEvent(type, canBubble, cancelable, view, clickCount, 
	    //           screenX, screenY, clientX, clientY, ctrlKey, 
	    //           altKey, shiftKey, metaKey, button, relatedTarget);
	    
	    var simulatedEvent = document.createEvent("MouseEvent");
	    	simulatedEvent.initMouseEvent(type, true, true, window, 1, 
			                              first.screenX, first.screenY, 
			                              first.clientX, first.clientY, false, 
			                              false, false, false, 0/*left*/, null);
	                                                                            
	    first.target.dispatchEvent(simulatedEvent);
	    //event.preventDefault();
	}
};

/**
 * Create image gallery
 *
 * @author Anton Shevchuk (http://anton.shevchuk.name)
 * @copyright (c) 2009 jQuery iPhone UI (http://iphone.hohli.com)
 * @license   Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
 * 
 * @version 0.2
 */
(function($){
    $.widget('ui.iGallery', {
        _init: function() {
            var _self = this;
            var $this = this.element;
            var width = parseInt($this.css("width").replace("px",""),10);
            
			$this.addClass('iphoneui')
			     .addClass('galleryui');
			
			// FIXME: need refactoring - wrapInner - it's bad
            $this.wrapInner('<div class="frame"></div>');

            this.frame = $this.find('.frame');
             
            var length = 0;
           
            // filter
            this.frame.children('br,hr').remove();
            
            // each image pack to div 
            this.frame.children().each(function(){
                length++;
                $(this).wrap('<div class="slide" id="slide_'+ER.app.page.topImg.ind+'"></div>');
                $(this).css({width:width});
                ++ER.app.page.topImg.ind;
            });
            
            this.oldX = 0;
            this.newX = 0;
            this.move = false;
            
            // ER.app.page.topImg.gap = it's margin between slides
            this.maxMargin = 0;
            this.minMargin = - ((width+ER.app.page.topImg.gap)*(length - 1)+(ER.app.page.topImg.gap*2));
            this.marginLeft = -ER.app.page.topImg.gap;
            
            // set container width
            this.frame.css({
                width:      (width+ER.app.page.topImg.gap)*length+ER.app.page.topImg.gap,
                marginLeft: this.marginLeft
            });
            
			// simple mouse gestures
            this.frame.mousedown(function(event) {
    		    _self.frame.stop(true, true);
    		    _self.oldX = event.pageX;
                _self.move = true;
                
    		    event.stopPropagation();
    		    event.preventDefault();
            });
            
            $(document).mouseup(function(event){
                if (_self.move) {
                    if (ER.app.page.topImg.getMargin) {
                        ER.app.page.topImg.getMargin = false;
                        _self.marginLeft = parseInt($("#igalleryWrap .frame").css("marginLeft").replace("px",""),10);
                    }
                    _self.move = false;
                    var el = Math.round(_self.marginLeft/(width+ER.app.page.topImg.gap));
                    _self.marginLeft = el * (width+ER.app.page.topImg.gap) - ER.app.page.topImg.gap;
                    _self._scroll();
                }
            });
            
            $(document).mousemove(function(event){
                if (_self.move && _self.oldX != 0) {
                    if (ER.app.page.topImg.getMargin) {
                        ER.app.page.topImg.getMargin = false;
                        _self.marginLeft = parseInt($("#igalleryWrap .frame").css("marginLeft").replace("px",""),10);
                    }
                    _self.newX = event.pageX;
                    
                    var diff = _self.marginLeft + (_self.newX - _self.oldX);                    
                    if (diff >= _self.minMargin && diff <= _self.maxMargin) {
                        _self.marginLeft =  _self.marginLeft + (_self.newX - _self.oldX);
                        _self._scroll();
                    }
                    _self.oldX = _self.newX;

                    //console.log("iGallery _self.oldX: " + _self.oldX)
                }
            });
        },
        _scroll: function() {
            this.frame.stop(true,true);
            this.frame.animate(
                {'marginLeft':this.marginLeft}, null, function() {
                    // Animation complete.
                    ER.app.page.topImg.highLight(ER.app.page.topImg.current());
                }
            );
        }
        
    });    
})(jQuery);

