/*
 * Pop ups
 */
var pitem_id = 0;

function popup(url, data, direction)
{
    // defaults
    var width   = 0,
        height  = 0,
        marginLimits = 200;

    // catch useless IE 6 and scoll to top
    if($.browser.msie && $.browser.version == '6.0')
    {
//        $('html, body').animate({scrollTop:0}, 'slow');
        $('.content').fadeOut(500);
    }


    if( data.width != undefined )
        width = data.width;

    if( data.height != undefined )
        height = data.height;

    // set pitem_id
    if( data.pitem_id != undefined )
        pitem_id = data.pitem_id;

    // only create pop up if needed
    if( $('#popup').length == 0 )
    {
        // create pop up
        var html = '<div id="popup_overlay">';
        html += '<div class="img_holder"></div>';

        html += '<div id="popup">';
        // controls
        // if project item
        if( data.pitem_id != undefined )
        {
            html += '<div class="controls">';
            html += '<a href="#" class="popupprevious"><img src="'+staticURI+'/images/btn_popup_left.gif" alt="X" /></a>';
            html += '<a href="#" class="popupnext"><img src="'+staticURI+'/images/btn_popup_right.gif" alt="X" /></a>';
        }
        else
            html += '<div class="controls small">';

        html += '<a href="#" class="popupclose"><img src="'+staticURI+'/images/btn_popup_close.gif" alt="X" /></a>\n';
        html += '<img src="'+staticURI+'/images/loader.gif" alt="Loading..." id="loader_gif" />';
        html += '</div>';

        // content
        html += '<div id="content"></div>';
        html += '</div></div>';
        $('body').append(html);

        // make sure it's on the screen and center popup
        var topOffset = ($(window).height() - $('#popup').height() ) / 2;
        if(topOffset < 50)
            topOffset = 50;
        
        $('#popup').css("top", topOffset  + "px");

        // close popup click
        $('.popupclose').click(function() {
            close_popup(true);
            return false;
        });

        $('#popup_overlay').click(function(e) {
            close_popup(e);
            return false;
        });

        $('.popupnext').click(function() {
            show_next();
            return false;
        });

        $('.popupprevious').click(function() {
            show_previous();
            return false;
        });

    }
    
    // show overlay!
    
        // do the work - overlay
        $('#popup_overlay').width($(window).width());
        $('#popup_overlay').height($(window).height());
        $('#popup_overlay .img_holder').width($(window).width());
        $('#popup_overlay .img_holder').height($(window).height());

        // show overlay if it isn't already'
        if( $('#popup_overlay').css('display') == 'none' )
            $('#popup_overlay').fadeIn(500);


    
    // place pop up in middle of screen
//   $('#popup').css("top", ( $(window).height() - $('#popup').height() ) / 2 + "px");
    $('#popup').css("left", ( $(window).width() - $('#popup').width() ) / 2 + "px");

    // ajax call
    $.post(url, data, function(returnData){
        // update content
        $('#popup > #content').html(returnData);
        
        // catch window size from img
        if( $('#popup > #content > img').length > 0 ) {
            height  = $('#popup > #content > img').height();
            width   = $('#popup > #content > img').width();
        }

        // catch window size from video
        if( $('#popup > #content > #container_wrapper').length > 0 ) {
            height  = $('#popup > #content > #container_wrapper').height();
            width   = $('#popup > #content > #container_wrapper').width();
        }

        // catch window size from embed
        if( $('#popup > #content > iframe').length > 0 ) {
            height  = $('#popup > #content > iframe').height();
            width   = $('#popup > #content > iframe').width();
        }

        // make sure image is loaded
        if($('#popupImage').length > 0) { // preload image
            jQuery.loadImages($('#popupImage').attr('src'), function(){

                // do the work - pop up
                $('#popup #content').css("width", width);
                $('#popup #content').css("left", ( $('#popup').width() - width ) / 2 + "px")

                // catch if popup is hidden and show it
                if( $('#popup #content').css('display') == 'none' ) {

                    // if direction is passed in animate in
                    $('#popup #content').fadeIn(500);
                }

                // make sure loader gif is faded out
                $('#loader_gif').fadeOut(500)
            });
        } else { // just show content

            // do the work - pop up
            $('#popup #content').css("width", width);
            $('#popup #content').css("left", ( $('#popup').width() - width ) / 2 + "px")

            // catch if popup is hidden and show it
            if( $('#popup #content').css('display') == 'none' ) {

                // animate in and add delay for embedded content (ie. Vimeo)
                if(url == '/popups/gmap')
                    $('#popup #content').show();
                else
                    $('#popup #content').delay(1500).fadeIn(500);
            }
            
            // make sure loader gif is faded out
            $('#loader_gif').delay(1500).fadeOut(500)
        }

    });
}

/*
 *Pop up controls
 */
function close_popup(e)
{
    // check that your not clicking inside main area for gmaps etc
    if(e !== true) // skip this and just close it on true
    {

//        console.log(e);
//        console.log( e.pageX +' > '+ parseInt($('#popup').css('left')) +' < '+ (parseInt($('#popup').css('left')) + $('#popup').width()) );
//        console.log( e.clientY +' > '+ parseInt($('#popup').css('top')) +' < '+ (parseInt($('#popup').css('top')) + $('#popup').height()) );
//        console.log('-------------------');

        // check to see if the click is inside the pop up div area
        if(e.pageX >= parseInt($('#popup').css('left')) - 20 &&
           e.pageX <= (parseInt($('#popup').css('left')) + $('#popup').width() + 20) &&
           e.clientY >= parseInt($('#popup').css('top')) - 20 &&
           e.clientY <= (parseInt($('#popup').css('top')) + $('#popup').height() + 20)
        )
        {
            return false;
        }
    }

    if($.browser.msie)
    {
        $('#popup_overlay').remove();
        if($.browser.msie && $.browser.version == '6.0')
        {
            $('.content').fadeIn(500);
        }
    }
    else
    {
        $('#popup_overlay').fadeOut(500, function() {
            $('#popup_overlay').remove();
        });
    }
    return true;
}

function close_and_open(pitem_id, direction)
{
    // show loader
    $('#loader_gif').fadeIn(500);

    $('#popup #content').fadeOut(500, function() {
        // call next one
        var data = {
            pitem_id: pitem_id
        };
        popup('/popups/project_item', data, direction);
    });
}

function show_next()
{
    // get list
    var poplist = $('.popupItem');
    var goto_pitem_id = 0;

    for(i=0; i < poplist.length; i++)
    {
        if(poplist[i].attributes.rel.value == pitem_id)
        {
            // get next item or loop over
            goto_pitem_id = poplist[0].attributes.rel.value;
            if(i+1 < poplist.length) {
                goto_pitem_id = poplist[(i+1)].attributes.rel.value;
            }
        }
    }

    close_and_open(goto_pitem_id, 'left');
}

function show_previous()
{
     // get list
    var poplist = $('.popupItem');
    var goto_pitem_id = 0;

    for(i=0; i < poplist.length; i++)
    {
        if(poplist[i].attributes.rel.value == pitem_id)
        {
            // get next item or loop over
            goto_pitem_id = poplist[(poplist.length-1)].attributes.rel.value;
            if(i-1 >= 0) {
                goto_pitem_id = poplist[(i-1)].attributes.rel.value;
            }
        }
    }

    close_and_open(goto_pitem_id, 'right');
}


/*
 * MAP
 */
var map;
var infowindow;

function loadMap() {

	// Preload images
	var mapIconArray = [];

	var bottleIcon = staticURI+"/images/icons/gmap_icon.png";
	var shadowIcon = staticURI+"/images/icons/gmap_icon_shadow.png";

	mapIconArray.push( bottleIcon, shadowIcon );

	// Load images
	//$.loadImages(mapIconArray);

	// Contact Us coords
	var latlng = new google.maps.LatLng(51.520565,-0.074134);

    var options = {
    		mapTypeControl: false,
    		zoom:15,
    		center: latlng,
    		mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map-canvas"), options);

    // Glenmorangie Marker
    var gIcon = new google.maps.MarkerImage(bottleIcon,
			    new google.maps.Size(24,24),
			    new google.maps.Point(0,0),
			    new google.maps.Point(0,24)
    );

    var gIconShadow = new google.maps.MarkerImage(shadowIcon,
    				  new google.maps.Size(0,0),
    				  new google.maps.Point(0,0),
    				  new google.maps.Point(0,0)
    );

    var shape = {
    			coord: [1,1,1,49,14,49,14,1],
    			type: 'poly'
    };


    var gMarker = new google.maps.Marker({
		position:latlng,
		map:map,
		icon:gIcon,
		shape: shape
    });
};


/*
 * Animate CSS clip property
*/
function animateClip(item,clipWidth,clipHeight,fromClip,toClip)
{
    var from = {property: fromClip};
    var to = {property: toClip};

    $(from).animate(to, {
        duration: 200,
        step: function() {
            clipMod = Math.round(this.property);
            clipTop = clipLeft = clipMod;
            clipRight = (clipWidth-clipMod);
            clipBottom = (clipHeight-clipMod);
            clipStringVal = new String('rect('+clipTop+'px '+clipRight+'px '+clipBottom+'px '+clipLeft+'px)');
            $(item).css('clip',clipStringVal);
        }});
}

/*
 * DOC READY
 */

$(document).ready(function(){

    // pop up project items
    if( $('.popupItem').length > 0) {
        
        $('.popupItem').live('click', function(){
            var data = {
                pitem_id: $(this).attr('rel')
            };
            popup('/popups/project_item', data, false);
            return false;
        });
        
        
        $('a.popupItem').hover(function(){
            //console.log('Over ' + $(this).attr('rel'));
            animateClip($(this).find('img'),220,168,0,3);
            
        },
            function(){
            //console.log('Out ' + $(this).attr('rel'));
            animateClip($(this).find('img'),220,168,3,0);
        });
        
    }

    // make sure not to follow hashes
    if( $('.supressPopupItem').length > 0) {
        $('.supressPopupItem').click(function(){
            return false;
        });
    }

    // footer
    $('.popupGmap').click(function(){
        var data = {width: 500, height: 500};
        popup('/popups/gmap', data, false);
        return false;
    });

    // back to top
    $('#backtotop').click(function()
    {
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
    $( window ).scroll( function () {
        backToTop();
    });

    // check scroll position to hide/show back to top link
    function backToTop()
    {
       // alert(($( window ).scrollTop() )+" : "+ ($(window).height()-400) );
        if( $( window ).scrollTop() > $(window).height()-400 )
        {
            
           // console.log("test");
            if(parseInt($('#backtotop').css('right')) < 0)
            {
                $('#backtotop').stop().animate( { "right":"20px" }, 400);
            }
        } 
        else
        {
            
            if(parseInt($('#backtotop').css('right')) > 0)
            {
                $('#backtotop').stop().animate( { "right":"-120px" }, 200);
            }
        }
    }

    // check btt on page load
    //backToTop();
    $('#backtotop').stop().animate( { "right":"-120px" }, 0);

    /*
     * Touch devices wipe functions
     */
    $(document).wipetouch({
        allowDiagonal: false,
        wipeLeft: function(result) {
            if( $('#popup').length > 0) {
                show_next();
            }

        },
        wipeRight: function(result) {
            if( $('#popup').length > 0) {
                show_previous();
            }
        }
    });
});
