/**
 * JS functions used on the product_detail.cfm page
 */

var getDefaultImage = 0;
var retain_size_id = 0;

var defult_frame_id = 0;
var defult_variation_id = 0;
var default_color = '';

var saved_frame_id = 0;
var saved_variation_id = 0;

var this_eye_width = 0;
var initial_eye_width = 0;
var vto_size_diff = 0;
var flag_initial = 1;
var vto_ready = 1;
var flag_initial_size_load = 1;
// var show_vto is defined in product_detail.cfm

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

$("#frame_size_id").change(function() {
    retain_size_id = this.value;
    // console.log('Retaining Size - ' + this.value);

    // output default size under specification tab
    if (flag_initial_size_load) {
        var default_size_value = $('#frame_size_id option:selected').text()
        $('#default_size_value').text(default_size_value);
        // console.log('initial_size_load default size: ' + default_size_value);
        flag_initial_size_load = 0;
    }

    // VTO code
    if (show_vto == 1) {
        // Get and store frame size change value (eye size in mm).
        // console.log($('#frame_size_id option:selected').html());
        if ($('#frame_size_id option:selected').html() == null) 
            // reload page on browser back action.
            window.location.reload();
        else {
            this_eye_width = $('#frame_size_id option:selected').html().slice(0, 2); //width is first 2 chars
            // console.log($('#frame_size_id option:selected').html());

            // in case when default size neq vto size
            if (flag_initial) {
                var thisImageEyeValue = $('#mainImage').attr('src');
                thisImageEyeValue = thisImageEyeValue.substring(thisImageEyeValue.length-7,thisImageEyeValue.length-4);
                // console.log('init eye: ' + thisImageEyeValue);
                initial_eye_width = thisImageEyeValue;
            }

            // if first change, save the initial value for reference
            /* if (flag_initial == 1) {
                initial_eye_width = this_eye_width;
            } */
            
            diff_width = this_eye_width - initial_eye_width;
            // console.log('diff_width: ' + diff_width);
            
            // in case when default size neq vto size
            if (flag_initial && diff_width != 0 && isNumber(diff_width)){
                // save diff_width as a session variable (session.vto_size_diff) via remoting
                var http = new XMLHttpRequest();
                http.open('GET', '/extensions/components/VTOfacade.cfc?method=saveSizeDiff&vto_size_diff=' + diff_width, false);
                http.send();
            }

            // console.log('flag_initial: '+flag_initial);
            
            if (flag_initial == 0) {
                // save diff_width as a session variable (session.vto_size_diff) via remoting
                var http = new XMLHttpRequest();
                http.open('GET', '/extensions/components/VTOfacade.cfc?method=saveSizeDiff&vto_size_diff=' + diff_width, false);
                http.send();
                // re-load the color frame (it will now load with adjusted size).
                loadSavedVtoFrame();
            }
            
            //reset the flag
            flag_initial = 0;
        }
    }
});


function retainSize() {
    $("#frame_size_id").val(retain_size_id);
 }


function initialRetainSize(x) {
    if (x < 100 && $("#frame_size_id").val() == 0)
        setTimeout(function() {initialRetainSize(x+1);}, 100);
    else
        $("#frame_size_id").change();
 }


$(document).ready(function() {
    initialRetainSize(0);
});


function openzoom(popurl)
{
    var gohref='/popup.cfm?id='+document.getElementById("frame_id").value+'&frame_color_id='+document.getElementById("frame_color_id").value;
    window.open(gohref,'imager','scrollbars=yes,resizable=1,width=565,height=600');
    return false;
}


function getVariationData(frameID){
    // This function must wait for the frame size to be reloaded in order to get the correct size.
    setTimeout(function() {setFrameCFC(frameID);}, 100);
}


function setFrameCFC(frameID){
    var color_id = document.getElementById("frame_color_id").value;
    // console.log(frameID,color_id);
    var size_id = parseInt(document.getElementById("frame_size_id").value);

    document.getElementById(color_id).setAttribute("class", "color_thumb color_selected");

    $.getJSON(
        window.location.protocol+'//'+window.location.hostname+'/extensions/components/frame.cfc?wsdl&frame_id='+frameID+'&frame_color_id='+color_id+'&frame_size_id='+size_id,
        { method : 'getFrameVariationsByOptions', returnformat : 'json', queryformat : 'column' },
        /*
            When the JSON data has returned, fire this callback function and pass in the JSON data  as it's argument.
        */
        populateVariationData
    );
    retainSize();
}


function populateVariationData(result){
    // console.log('populateVariationData');
    // console.log(result);
    // console.log(result.DATA.COLOR_NAME[0]);
    // console.log(result.DATA.FILE_NAME[0]);

    document.getElementById("frame_color_caption").innerHTML= result.DATA.COLOR_NAME[0];
    document.getElementById("frame_color_caption_2").innerHTML= result.DATA.COLOR_NAME[0];
    document.getElementById("regularPrice").innerHTML= "$" + result.DATA.PRICE[0].toFixed(2);
    document.getElementById("sku").innerHTML = result.DATA.FPC[0];
    $("#vto_size").text($('#frame_size_id option:selected').text());

    if (result.DATA.COLOR_DEFAULT[0].length > 0) {
        document.getElementById("frame_color_caption").innerHTML = "Showing " + result.DATA.COLOR_DEFAULT[0];
    } else {
        document.getElementById("frame_color_caption").innerHTML = result.DATA.COLOR_NAME[0];
    }

    // update variation id hidden field
    document.getElementById("variation_id").value=result.DATA.ID[0];
    // console.log('variation_id: '+result.DATA.ID[0]);

    if (show_vto == 1) {
      checkVTOready();
    }

    // update add lens to frame link
    $.getJSON(
        window.location.protocol+'//'+window.location.hostname+'/extensions/components/frame.cfc?wsdl&frame_id='+document.getElementById("frame_id").value+'&frame_color_id='+document.getElementById("frame_color_id").value+'&frame_size_id='+$('#frame_size_id option:selected').val(),
        { method : 'getFrameVariationsByOptions', returnformat : 'json', queryformat : 'column' },
        /*
            When the JSON data has returned, fire this callback function and pass in the JSON data  as it's argument.
        */
        updateAddLensesLink
    );

    var http = new XMLHttpRequest();
    http.open('HEAD', '/images/catalog/live/imageLibrary/large/' + result.DATA.FILE_NAME[0], false);
    http.send();

    if (http.status == 404)
        result.DATA.FILE_NAME[0] = '';

    if (result.DATA.FILE_NAME[0] == '') {
        document.getElementById("mainImage").src='/images/static/img_not_avail_large.jpg';
        } else {
        document.getElementById("mainImage").src='/images/catalog/live/imageLibrary/large/' + result.DATA.FILE_NAME[0];
    }
}


function updateAddLensesLink(result2) {
    document.getElementById("add_lens_frame").href='/lens_wizard.html?id='+document.getElementById("frame_id").value+'&variation_id='+result2.DATA.ID[0];
}


/***********************
 * VTO functions start *
 ***********************/

function getFrameInfo() {
    var frameInfo = new Array();
    frameInfo[0]=$('#frame_id').val();
    frameInfo[1]=$('#variation_id').val();
    return frameInfo;
}


// load saved color frame in case of size change
// we need 1 sec delay here to allow data to load.
function loadVtoTimer(){
    // console.log("loadVtoTimer");
    if (show_vto == 1) {
        var t = setTimeout("loadVtoFrame()", 1000);
    }
}


function loadVtoFrame() {
    // console.log('show_vto: '+show_vto);
    if(vto_ready) {
        $('#flash_app')[0].contentWindow.sendFrameInfo($('#frame_id').val(),$('#variation_id').val());
        // console.log('loading new frame');
        $('#saved_vto_frame_message').text('');
        $('#saved_vto_frame_message').css('border-color','#fff');
      // store color frame/variation ids to be retrieved for size changes
      saved_frame_id = $('#frame_id').val();
      saved_variation_id = $('#variation_id').val();
      // console.log('loadVtoFrame|saving:'+saved_frame_id+':'+saved_variation_id);
    } else {
        $('#flash_app')[0].contentWindow.sendFrameInfo(defult_frame_id,defult_variation_id);
        // console.log('loading DEFAULT frame: '+defult_frame_id+' '+defult_variation_id);
        $('#saved_vto_frame_message').html('Try-On image shown: '+default_color+', size: <span id="vto_size"></span><br>Try-On '+$('#frame_color_caption_2').text()+' image is not available.');
        $('#saved_vto_frame_message').css('border-color','#ccf');
        $("#vto_size").text($('#frame_size_id option:selected').text());
        // store color frame/variation ids to be retrieved for size changes
        saved_frame_id = defult_frame_id;
        saved_variation_id = defult_variation_id;
    }
}


function loadSavedVtoFrame() {
    $('#flash_app')[0].contentWindow.sendFrameInfo(saved_frame_id,saved_variation_id);
    // console.log('loadSAVEDVtoFrame:'+saved_frame_id+':'+saved_variation_id);
    $("#vto_size").text($('#frame_size_id option:selected').text());
}


$(document).ready(function() {
    // initial frame load -- save color frame/variation ids to be retrieved for size changes
    defult_frame_id = $('#frame_id').val();
    defult_variation_id = $('#variation_id').val();
    default_color = $('#frame_color_caption_2').text();

    saved_frame_id = defult_frame_id;
    saved_variation_id = defult_variation_id;
    // console.log('[on doc ready] saving:'+saved_frame_id+':'+saved_variation_id);
});


function checkVTOready() {
    // console.log($('#frame_id').val(),' ',$('#variation_id').val());
    $.getJSON(
        window.location.protocol+'//'+window.location.hostname+'/extensions/components/VTOfacade.cfc?wsdl&frame_id='+$('#frame_id').val()+'&frame_variation_id='+$('#variation_id').val(),
        { method : 'checkIfVtoReady', returnformat : 'json' },
        /*
            When the JSON data has returned, fire this callback function and pass in the JSON data  as it's argument.
        */
        populateVTOdata
    );
}


function populateVTOdata(result) {
    vto_ready = result;
    // console.log('vto ready: '+vto_ready);
}


function shareVTO(dressing_room_id) {
    // console.log('shareVTO: '+dressing_room_id);
    $.ajax({
        url: '/extensions/components/VTOfacade.cfc?method=getEnc&id='+dressing_room_id,
        dataType: 'json',
        cache: false,
        success: function(response) {
            var u = '/facebook_share.cfm?ts=' + response.TS + '&id=' + response.EID;
            $.modal('<iframe src="'+u+'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:410px; height:485px;" allowTransparency="true"></iframe>', {
                closeHTML:'<a href="javascript: void(0);"><img alt="Close" width="42" height="42" src="/images/static/btn_close_x.png" class="frame_page_modal_close" /></a>',
                opacity:80,
                overlayClose:true,
                overlayCss: {backgroundColor:'#ccc'},
                containerCss:{
                    height:640,
                    padding:0,
                    width:410
                },
                overlayClose:true
            });
        },
        error: function(ErrorMsg) {
            // console.log('Error');
        }
    })
};

/** /VTO functions end */



