var j = jQuery.noConflict();    //so jquery does not conflict with prototype

j(document).ready(function() {
	// for preview
	j("#preview_front_spot_uv").bind('click', {face:j('#front_id'), spot:j('#front_spot_id')}, popupSpotPreview);
	j("#preview_back_spot_uv").bind('click', {face:j('#back_id'), spot:j('#back_spot_id')}, popupSpotPreview);
	
	j('#front_spot_id').bind("spotPreviewCloseFront", function(evt, isCancel, url, spot) {
            if (!isCancel) {
                updateSpotImg(j('#front_spot_id'), spot, url);
            }
        }
    );
    j('#back_spot_id').bind("spotPreviewCloseBack", function(evt, isCancel, url, spot) {
            if (!isCancel) {
                updateSpotImg(j('#back_spot_id'), spot, url);    
            }
        }
    );
	
	// for remove
	j("#remove_front_spot_uv").bind('click', {isFront: 1, spot: j('#front_spot_id'), selectedItem: j('#itemId_selector').attr('value')}, removeSpot);
	j("#remove_back_spot_uv").bind('click', {isFront: 0, spot: j('#back_spot_id'), selectedItem: j('#itemId_selector').attr('value')}, removeSpot);

    // Spot UV popup
    j("#popupSpotUV").dialog({
        title       : "About Spot UV",
        draggable   : true,
        maxHeight   : 800,
        minHeight   : 300,
        width       : 800,
        height      : 'auto',
        modal       : true,
        autoOpen    : false,
        position    : 'top'
    });
    j("#spotUVGuidelines, .learnmore").bind("click", function() {
        j("#popupSpotUV").dialog("option", "height", 400);
        j(".spotUVPopup .spotUVReadMore").hide();
        j('#popupSpotUV').dialog('open');
        return false;
    });
    j("#popupSpotUV a").click(function(){
        j("#popupSpotUV").dialog("option", "height", 800);
        j(".spotUVPopup .spotUVReadMore").show();
        return false;
    });
});

function popupSpotPreview(evt) {
	if (evt.data.spot.children('img').length == 0) {
		return false;
	}
	
	// for face
	var faceId = getUploadedFileId(evt.data.face);	
	var facePaths = evt.data.face.children('img').attr('src').split('=');
	var parent = new Object();
	parent.fileUploadedId = faceId;
	parent.imglowres = facePaths[facePaths.length - 1];
	
	// for spot
	var spotId = getUploadedFileId(evt.data.spot);	
	var spotPath = evt.data.spot.children('img').attr('src').replace('th', 'low');	
	var spotThreshold = getSpotThreshold(evt.data.spot);
	
	var spot = {fileUploadedId: spotId, imglowres: spotPath};
	
	// other required params 
	var isFront = evt.data.face.attr('id') == 'front_id' ? 1 : 0;
	var isLandScape = getDesignOrientation();	
	var isThresholdSliderHidden = true;
	
	spotPreview.open(0, spot, parent, isFront, spotThreshold, isLandScape, isThresholdSliderHidden);
	return false;
}

function getUploadedFileId(element) {
	switch (element.attr('id')) {
		case 'front_id':
			return j("input[name='FileId[1]']").attr("value");
		case 'front_spot_id':
			return j("input[name='FileId[1001]']").attr('value');
		case 'back_id':
			return j("input[name='FileId[2]']").attr('value');
		case 'back_spot_id':
			return j("input[name='FileId[1002]']").attr('value');
	}
}

function setUploadedFileId(element, value) {
	switch (element.attr('id')) {
		case 'front_id':
			return j("input[name='FileId[1]']").attr("value", value);
		case 'front_spot_id':
			return j("input[name='FileId[1001]']").attr('value', value);
		case 'back_id':
			return j("input[name='FileId[2]']").attr('value', value);
		case 'back_spot_id':
			return j("input[name='FileId[1002]']").attr('value', value);
	}
}

function getDesignOrientation() {
	if (j("input[name='imageOrientation']").attr("value") == 'landscape')
		return true;
	else
		return false;
}

function getSpotThreshold(element) {
	if (element.attr('id') == 'front_spot_id') {		
		return j("input[name='Threshold[1001]']").attr('value');
	} else {
		return j("input[name='Threshold[1002]']").attr('value');
	}
}

function setSpotThreshold(element) {
	if (element.attr('id') == 'front_spot_id') {		
		return j("input[name='Threshold[1001]']").attr('value', j('.threshold-bar.slider').slider('value'));
	} else {
		return j("input[name='Threshold[1002]']").attr('value', j('.threshold-bar.slider').slider('value'));
	}
}


function updateSpotImg(element, spot, url) {
	var file = {id: spot.fileUploadedId, name: spot.filename, path: url};
	var img = j('<img />').attr({src: file.path, alt: file.name, width: element.width(), height: element.height()});
	
	element.empty().append(img);
	setSpotThreshold(element);
}

function removeSpot(evt) {
	var removed = confirm("Delete Spot File?");
	
	if (removed) {	
		j.ajax({
            type: "POST",
            url: "main.php?X=removeSpotFile",
            data: {fileUploadedId: getUploadedFileId(evt.data.spot), isFront: evt.data.isFront, selectedItem: evt.data.selectedItem},
            success: function(response) {
            	if (evt.data.isFront == 1) {
            		j('div.front-spot').replaceWith(response.data);
            	} else {
            		j('div.back-spot').replaceWith(response.data);
            	}
            	
            	setUploadedFileId(evt.data.spot, '0');
            	j("input[name='hasSpotUV']").attr("value", 0);
            	j('div.newQty .option_text .input_container').empty().html(response.price);
            },
            dataType: "json",
            error: function(response) {
            	console.log("error");
            }
        });
	}
}
