var phototype_width = 1;
var phototype_height = 1;
var phototype_unit = "cm";
var selection_size_factor=30;
var image_width = 425;
var image_height = 319;
var ias; //imgAreaSelect API object
var selectableImage; //imgAreaSelect image object
var imagepath; //path to the uploaded image
var country; //2 letters code of the selected country
var photo_type; //the id of the photo type (unique per country)
$.extend($.imgAreaSelect, {
    animate: function (fx) {
        var start = fx.elem.start, end = fx.elem.end, now = fx.now,
                curX1 = Math.round(start.x1 + (end.x1 - start.x1) * now),
                curY1 = Math.round(start.y1 + (end.y1 - start.y1) * now),
                curX2 = Math.round(start.x2 + (end.x2 - start.x2) * now),
                curY2 = Math.round(start.y2 + (end.y2 - start.y2) * now);
        fx.elem.ias.setSelection(curX1, curY1, curX2, curY2);
        fx.elem.ias.update();
    },
    prototype: $.extend($.imgAreaSelect.prototype, {
        animateSelection: function (x1, y1, x2, y2, duration) {
            var fx = $.extend($('<div/>')[0], {
                ias: this,
                start: this.getSelection(),
                end: { x1: x1, y1: y1, x2: x2, y2: y2 }
            });

            if (!$.imgAreaSelect.fxStepDefault) {
                $.imgAreaSelect.fxStepDefault = $.fx.step._default;
                $.fx.step._default = function (fx) {
                    return fx.elem.ias ? $.imgAreaSelect.animate(fx) :
                            $.imgAreaSelect.fxStepDefault(fx);
                };
            }

            $(fx).animate({ cur: 1 }, duration, 'swing');
        }
    })
});

$(document).ready(function(){
    initUpoadify();

    $('.navi a').live('click', function(event){
        // cancel the default action.
        // same as using "return false;" as the last line of this code block.
        event.preventDefault();

        /* If you have multiple callbacks of the same type this prevents
         the rest of the callbacks from being executed. */
        event.stopImmediatePropagation();
    });
//todo:make this 'live' binding
    $('.image-hint-indicator').hover(function(){
        $('#'+$(this).attr('rel')).fadeIn();
    });

    $('.image-hint-indicator').mouseout(function(){
        $('#'+$(this).attr('rel')).fadeOut();
    });

    //Tabs
    $('div.css-tabs-wrapper').tabs('div#main-container > div', {effect: 'fade',
        history: true,
        onBeforeClick: function(event, i) {
            // get the pane to be opened
            var pane = this.getPanes().eq(i);
            // // only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
            if (pane.is(":empty")) {					// load it with a page specified in the tab's href attribute
                pane.load(this.getTabs().eq(i).attr("href"));
            }
        }
    });

//todo: add 2 letters file for palestine, tonga, Uganda, USCIS in spec.php

    $('.countryspec').live('click', function(){
        $('#spec-container').load($(this).attr('href'));
        return false;
    });

    //load photo types select-box after country is selected
    updatePhotoTypes();
    $('#phototype').live('change',function(){
        photo_type = $(this).attr('selectedIndex') + 1;
        //reload template
        selectStart(selectableImage, ias.getSelection());
    });

    initScrollable();

}); //end document.ready

function initScrollable() {
    // initialize scrollable and return the programming API
    var api = $("#scroll").scrollable({
        items: '#tools',
        history: true
        // use the navigator plugin
    }).navigator().data("scrollable");


    // this callback does the special handling of our "intro page"
    api.onBeforeSeek(function(e, i) {

        // when on the first item: hide the intro
        if (i) {
            $("#intro").fadeOut("slow");

            // dirty hack for IE7-. cannot explain
            if ($.browser.msie && $.browser.version < 8) {
                $("#intro").hide();
            }

            // otherwise show the intro
        } else {
            $("#intro").fadeIn(1000);
        }

        // toggle activity for the intro thumbnail
        $("#t0").toggleClass("active", i == 0);
    });

    // a dedicated click event for the intro thumbnail
    $("#t0").click(function() {
        // seek to the beginning (the hidden first item)
        $("#scroll").scrollable().begin();
        if (selectableImage != null) {
            selectableImage.imgAreaSelect({remove:true});
        }
    });
}
function initUpoadify() {
    $("#fileUpload").uploadify({
        "uploader"       : "uploadify.swf",
        "script"         : "uploadify.php",
        "cancelImg"      : "images/cancel.png",
        "fileDesc"       : "Images (*.jpg, *.jpeg)",
        "fileExt"        : "*.jpg;*.jpeg",
        "sizeLimit"      : "3145728",
        'wmode'          : 'transparent',
        'hideButton'     : true,
        "auto"           : true,
        "width"          : "193",
        "height"         : "50",
        "multi"          : false,
        "scriptData"     : {'<?php echo session_name(); ?>':'<?php echo session_id(); ?>'},
        onComplete       : uploadComplete,
        onError          : function (evt, queueID, fileObj, errorObj) {alert("error uploading: "+errorObj.info);}
    });
}

function uploadComplete(event, ID, fileObj, response, data) {
    //move to next step in the wizard
    wiz_goto(2);
    imagepath = response;
    //load image into face selection area
    loadImage('image-select-wrapper', 'getImage.php?type=preview&image='+imagepath, function(img) {
        selectableImage = img;
        image_width = img.width();
        image_height = img.height();
        updatePreview(img);
        setImageSelect(img);
        preview(img, ias.getSelection());
    });
}

/*
 update the preview image with the given image, and set the width and height vars that are used in 'preview'
 */
function updatePreview(img) {
    $('#preview-wrapper > img').attr('src',img.attr('src'));
}
/*
 create imgAreaSelect around the given image
 */
function setImageSelect(img) {
    //Image select
    ias = img.imgAreaSelect({
        aspectRatio: phototype_width+':'+phototype_height,
        onSelectChange: preview,
        x1: 10,
        y1: 10,
        x2: 10+phototype_width*selection_size_factor,
        y2: 10+phototype_height*selection_size_factor,
        keys: { arrows: 10, shift: 1 },
        onSelectEnd: selectEnd,
        onInit: selectStart,
        onSelectStart: selectStart,
        handles: true,
        fadeSpeed: 10,
        instance: true,
        autoHide: false,
        parent: '#mark-face-wrapper',
        zIndex:10
    });
}

function goto_final() {
    wiz_goto(3);
    var selection = ias.getSelection();
    loadImage('fan-wrapper', 'getImage.php?type=passport&image='+imagepath+'&x1='+selection.x1+'&x2='+selection.x2+'&y1='+selection.y1+'&y2='+selection.y2+'&imagewidth='+image_width);
    trackAnalytics('/wizard-step3');
}

function wiz_goto(step) {
   $("#scroll").scrollable().seekTo(step,500);
    trackAnalytics('wizard-step'+step);
}

function loadImage(div_id, path, callback) {
    var img = new Image();
    $(img)
        // once the image has loaded, execute this code
            .load(function () {
        $('#'+div_id+' > img').replaceWith($(this));
        if (callback != undefined) {
            callback($(this));
        }
    })

        // if there was an error loading the image, react accordingly
            .error(function () {
        // notify the user that the image could not be loaded
    })

        // *finally*, set the src attribute of the new image to our image
            .attr('src', path);
}

/*
sets the preview image to the right dimensions and location
 */
function preview(img, selection) {

    var preview_width = parseInt($('#preview-wrapper').css('width').substring(0,$('#preview-wrapper').css('width').length-2));
    var preview_height = parseInt($('#preview-wrapper').css('height').substring(0,$('#preview-wrapper').css('height').length-2));

    var scaleX = preview_width / (selection.width || 1);
    var scaleY = preview_height / (selection.height || 1);

    $('img.preview').css({
        width: Math.round(scaleX * image_width) + 'px',
        height: Math.round(scaleY * image_height) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
}

function selectStart(img,selection) {
    $('.imgareaselect-selection').load("template.php?country="+country+"&code="+photo_type);
}

function selectEnd(img,selection) {
//    $('#x1').val(selection.x1);
//    $('#y1').val(selection.y1);
//    $('#w1').val(selection.width);
//    $('#h1').val(selection.height);
//    $('#imgwidth').val($('#selectimg').width());
//    $('#imgheight').val($('#selectimg').height());
    preview(img, selection);
}

function updatePhotoTypes() {
    country = $('#country option:selected').val();
    $('#phototype').load('photoTypes.php',{'country':country},
                        function(responseText, textStatus, XMLHttpRequest){
                            //set selection aspect ratio
                            //todo: load SCRIPT separately since it's not evaluated in IE
                            var w_h = types_sizes[$('#phototype option:selected').val()];
                            phototype_width = w_h['w'];
                            phototype_height = w_h['h'];
                            phototype_unit = w_h['u']==' cm'?'cm':'inch';
                            photo_type = ($('#phototype').attr("selectedIndex"))+1;
                            if (ias != undefined) {
                                ias.setOptions({aspectRatio: phototype_width+':'+phototype_height});
                                ias.animateSelection(10, 10,
                                        10+phototype_width*selection_size_factor,
                                        10+phototype_height*selection_size_factor, 'slow');
                                preview($('#image-select-wrapper >img'), ias.getSelection());
                                selectStart(selectableImage, ias.getSelection());
                            }
                            //set selection preview to the right size
                            $('#preview-wrapper').animate({'width':150*phototype_width/phototype_height});
                            //set background of end result image (fan) in step 3 according to photo dimensions
                            $('#fan-wrapper').css('background-image','url(images/fans/'+phototype_width+'x'+phototype_height+'.png)');
                            //set sentence in step3 '3 US passport photos (2x2")
                            $('#photo-description').html(getNumberOfPhotos(phototype_width,phototype_height, phototype_unit, true) +
                                    " " +
                                    country_name['countrian'] +
                                    " " +
                                    $('#phototype option:selected').val() +
                                    " photos");
                            $('#photo-size').html('( '+phototype_width+' x '+phototype_height+w_h['u']+' )');
                        });
}

function getPassports() {
    var selection = ias.getSelection();
    var url = 'getImage.php?type=sheet&image='+imagepath+'&x1='+selection.x1+'&x2='+selection.x2+'&y1='+selection.y1+'&y2='+selection.y2+
            '&imagewidth='+image_width+'&phototype_width='+phototype_width+'&phototype_height='+phototype_height+'&phototype_unit='+phototype_unit
    $('#download-link').attr('href',url);
    trackAnalytics('/getImage.php?type=sheet')
    return true;
}

/*
calculate how many photos can fit into 10x15cm paper (4x6")
 */
function getNumberOfPhotos(width, height, unit, includeLogo) {
    if (unit=='cm') {
        width = width/2.51;
        height = height/2.51;
    }
    var pir = Math.floor( 6/width );
    var pic = Math.floor( 4/height );
    return (includeLogo ? pir*pic-1 : pir*pic);
}
  				  
  				  
/*
 track google analytics pages in Ajax
 page syntax is '/pagefilename1'
 */
function trackAnalytics(page) {
    _gaq.push(['_trackPageview', page]);
}
