/**
 * Copyright (C) 2009 TopCoder Inc., All Rights Reserved.
 */
 /**
 * 
 * This is a main js file to handle the style quiz functions.
 * 
 * @author TopCoder
 * @version 1.0
 *
 */

$(function() {
    var step = 1; //setp No.
    var MAX; //step sum
    var result;
    
    //define destination URLs and actions
    var BACKEND_URL = '/quiz/StyleQuizServlet';
    var PRINT_URL = '/quiz/print.jsp';
    var GET_QUESTIONS_ACTION = "getQuestions";
    var CACULATE_STYLE_ACTION = "calculateStyle";
    var GET_PROD_STYLE_ACTION = "getProducts";	
	var GET_OPTION_ACTION = "getOption";
	var GET_INTRO_IMAGE_ACTION = "getIntroductionImages";
	
	var intro_images = new Array();
	var questions = new Array();
	var selections = new Array();
	
	var current_selection;
	
	var x,y,v;
		
	//display modal windows
    //var modal = $("#quizWin").overlay({api:true,expose:{color: '#000',opacity: 0.9,closeOnClick:false},close:'#btnClose',closeOnClick:false});
    //modal.load();	
		
	//get introduction images
    $.ajax({
  		type: "GET",
  		url: BACKEND_URL + "?action=" + GET_INTRO_IMAGE_ACTION,
  		dataType: "xml",
  		success: function(xml){
  			
  			//handle error
  			if ($(xml).find("Error").size() > 0) {
  				alert("The Style Quiz is not available at this time");
  				modal.close();
  			} else {  				
    			$(xml).find("Image").each(function(){
  				var arr = new Array($(this).text());
  				intro_images = $.merge(intro_images, arr);
  				});
  		
  			//display introduction images
  			if (intro_images.length == 2) {
					$("#quizContent #leftIntroImg img").attr( 'src', intro_images[0] );
					$("#quizContent #rightIntroImg img").attr( 'src', intro_images[1] );
  				$("#quizContent #leftIntroImg").css("display","block");
  				$("#quizContent #rightIntroImg").css("display","block");
  				DD_belatedPNG.fix('#leftIntroImg img,#rightIntroImg img');
  			}
  			}
  		}
	});
	
    //get questions
    $.ajax({
  		type: "GET",
  		url: BACKEND_URL + "?action=" + GET_QUESTIONS_ACTION,
  		dataType: "xml",
  		success: function(xml){
  			//handle error
  			if ($(xml).find("Error").size() > 0) {
  				alert("The Style Quiz is not available at this time");
  				modal.close();
  			}
  			
  			$(xml).find("Question").each(function(){
  				var question = new Object();
  				question.id = $(xml).find("Id").text();
  				question.desc = $(xml).find("Description").text();
  				question.type = $(xml).find("Type").text();
  				question.options = new Array();
  				$(this).find("Option").each(function(){
  					var option = new Object();
  					option.id = $(this).find("Id").text();
  					option.url = $(this).find("ImageUrl").text();
  					option.desc = $(this).find("Description").text();
  					question.options = $.merge(question.options, new Array(option));
  				});
  				questions = $.merge(questions, new Array(question));
  				//set the max option number
  				MAX = questions.length;
  				//generate steps
  				var stepsHtml = "";
  				for (var j=0; j < MAX; j++) {
  					stepsHtml += "<li></li>"
  				}
  				$('#quizContent #info .steps').html(stepsHtml);
  			});	
  		}
	});    

    //fix png for IE
    //$('#quizWin').pngFix();
    

    //function to integration with serverside
    function afterSelect(stepNo) {
    	
        //go to result
        if (stepNo == MAX+1) {
        	        
            $('#quizStep').hide();
            $('#info h1').fadeOut();
            $('#info h2').fadeOut();
            $('#info #stepInfo').fadeOut();
            $('#info .steps').fadeOut(function(){
                $('#info').animate({"width":"+=254","left":"+=72"}, "slow", function() {
                    $('#quizResult').show();
                    $('#quizResult .right').fadeIn();
                    $('#quizResult h1').fadeIn();

                    //Caculate styles
                    var optionIdString = "";
                    for (var i=0; i < selections.length; ++i) {
                    	if (i != selections.length - 1) {
                    		optionIdString += selections[i] + ",";
                    	} else {
                    		optionIdString += selections[i];
                    	}
                    }
                    
                    $.ajax({
  						type: "GET",
  						url: BACKEND_URL + "?action=" + CACULATE_STYLE_ACTION + "&optionIds=" + optionIdString,
  						dataType: "xml",
  						success: function(xml){
  							//handle error
  							if ($(xml).find("Error").size() > 0) {
  								alert("The Style Quiz is not available at this time");
  								modal.close();
  							}
  							result=$(xml).find("Id").text();
  							var url = $(xml).find("ImageUrl").text();
  							var desc = $(xml).find("Description").text();
  							var urlFrame = "url('images/resultLeftMask_"+result+".png')";
                    		
                    		$('#quizResult .leftMask').css('backgroundImage', urlFrame );
                    		$('#quizResult .style #styleImg').attr( 'src', url );
                    		$('#quizResult .style #styleImg').attr( 'alt', desc );                    		
                    		$('#quizResult .right h2').text(result);
                    		$('#quizResult .right p').text(desc);
                    		
                    		$('#quizResult .leftMask').show().animate({"height":"+=336"}, "fast", function() {
                        		$('#quizResult .style').fadeIn(); 
                        		
                        		//set hover function
                        		$('#quizResult .leftMask').hover(function(event){
        						    $(this).removeClass("unhover").addClass("hover");
        							x=$('#quizResult').offset().left;
        							y=$('#quizResult').offset().top;
        							v=$('#quizResult .style #styleImg').attr("alt");
        							//$('#tip').text(v.toString()).css({left:event.pageX-x+10,top:event.pageY-y-20,display:"block"});
    							},function(){
        							$(this).removeClass("hover").addClass("unhover");
        							//$('#tip').hide();
    							});
    							$('#quizResult .right .scrollable div.items div').bind("mousemove",function(event){
        							if(x==undefined||y==undefined) return;
        							//$('#tip').css({left:event.pageX-x+10,top:event.pageY-y-20});
    							});
                        		
                        		//reset images
                        	 	$('#quizResult .right .items').html("");

                        		for(var i=0; i < selections.length; ++i){
                        		
                        		$.ajax({
  									type: "GET",
  									url: BACKEND_URL + "?action=" + GET_OPTION_ACTION + "&optionId=" + selections[i],
  									dataType: "xml",
  									success: function(xml){  
  										//handle error
  										if ($(xml).find("Error").size() > 0) {
  											alert("The Style Quiz is not available at this time");
  											modal.close();
  										}  										
  										var opt_id=$(xml).find("Id").text();
  										var opt_url=$(xml).find("ImageUrl").text();
  										var opt_desc=$(xml).find("Description").text();

                   	    				$('#quizResult .right .items').append('<div><img class="png" src="' + opt_url + '" height="78" width="77" alt="' + opt_desc +'"/></div>');
                   	    				
                   	    				//set up product carousel
    										$("div.scrollable").scrollable({size:3,clickable:false});
    
    										//product carousel hover/tip    										
    										$('#quizResult .right .scrollable div.items div').hover(function(event){
        										//$(this).removeClass("unhover").addClass("hover");
        										//x=$('#quizResult').offset().left;
        										//y=$('#quizResult').offset().top;
        										//v=$('img',$(this)).attr("alt");
        										//$(this).css({ cursor: "pointer", background: "url(images/itemBG.png) 0px 0px no-repeat" });
        										//$('#tip').text(v.toString()).css({left:event.pageX-x+10,top:event.pageY-y-20,display:"block"});
    										},function(){
    												//$(this).css({ cursor: "pointer", background: "url(images/itemBGOff.png) 0px 0px no-repeat" });
        										//$(this).removeClass("hover").addClass("unhover");
        										//$('#tip').hide();
    										});
    										$('#quizResult .right .scrollable div.items div').bind("mousemove",function(event){
        										//if(x==undefined||y==undefined) return;
        										//$('#tip').css({left:event.pageX-x+10,top:event.pageY-y-20});
    										});    										
                                	}                                	
  								}); 
  								}     								
  								$('#btnPrint').click(function () { 
      								window.open(PRINT_URL + "?styleId=" + result + "&optionIds=" + optionIdString); 
    							});
    							$('#btnRequest').click(function () { 
      								parent.goToConsultation(result);
    							});    		                       
                    		});
  						}
  					});                   
                    
                });
            });
        }
    }

    //Start Quiz
    var lck_start=false;
    $('#info #btnStart').click(function() {
        if(lck_start){
            return;
        }else{
            lck_start=true;
        }
        //hide introduction images
        $("#quizContent #leftIntroImg").hide();
  		$("#quizContent #rightIntroImg").hide();
  		
        $('#quizContent .bg').fadeOut();
        $('#info h1').fadeOut();
        $('#info p').fadeOut();
        $(this).fadeOut();
        $('#info').animate({"width":"-=167","left":"+=84"}, "normal", function() {
            $('#info h1').css({background:'url("images/centerTextSmall.png") no-repeat',height:144,width:164,marginTop:0}).fadeIn();
            $('#info h2').fadeIn();
            setSteps(step);
            $('#info #stepInfo').fadeIn();
            $('#info .steps').fadeIn();
            $('#quizStep .leftMask').animate({"height":"+=398"}, "fast");
            $('#quizStep .rightMask').animate({"height":"+=398"}, "fast", function() {            	
                $('#quizStep .styles').fadeIn("fast",function(){
                    $('#quizStep #leftStyle').attr( 'src', questions[step -1].options[0].url );
        			$('#quizStep #rightStyle').attr( 'src', questions[step -1].options[1].url );
        			$('#quizStep #leftStyle').attr( 'alt', questions[step -1].options[0].desc );
        			$('#quizStep #rightStyle').attr( 'alt', questions[step -1].options[1].desc );
        			$("#stepInfo").html(step + " of " + MAX);
        			$('#quizStep #leftStyle').fadeIn("fast");
        			$('#quizStep #rightStyle').fadeIn("fast");
        			$('#quizStep .leftMask img').show();
                    $('#quizStep .rightMask img').show();                
                });
            });
        });
        return false;
    });

    //left/right style hover
    $('#quizStep .leftMask').hover(function(event) {
        $(this).css({backgroundPosition:"0 0","cursor":"pointer"})
        $('#quizStep .leftMask img').css("right","13px");
        
        //show description text
        $(this).removeClass("unhover").addClass("hover");
        x=$('#quizStep').offset().left;
        y=$('#quizStep').offset().top;
        v=$('#quizStep #leftStyle').attr("alt");
        //$('#tip').text(v.toString()).css({left:event.pageX-x+10,top:event.pageY-y-20,display:"block"});
        
    }, function() {
        $(this).css("backgroundPosition", "0 -398px")
        $('#quizStep .leftMask img').css("right","3px");
        
        $(this).removeClass("hover").addClass("unhover");
        //$('#tip').hide();
    });
    $('#quizStep .rightMask').hover(function(event) {
        $(this).css({backgroundPosition:"0 0","cursor":"pointer"})
        $('#quizStep .rightMask img').css("left","13px");
        
        //show description text
        $(this).removeClass("unhover").addClass("hover");
        x=$('#quizStep').offset().left;
        y=$('#quizStep').offset().top;
        v=$('#quizStep #rightStyle').attr("alt");
        //$('#tip').text(v.toString()).css({left:event.pageX-x+10,top:event.pageY-y-20,display:"block"});
    }, function() {
        $(this).css("backgroundPosition", "0 -398px")
        $('#quizStep .rightMask img').css("left","3px");
        
        $(this).removeClass("hover").addClass("unhover");
        //$('#tip').hide();
    });

    //select left style
    $('#quizStep .leftMask').click(function() {   
    	$('#quizResult .leftMask').removeClass("hover").addClass("unhover");
        //$('#tip').hide(); 	
        $('#quizStep .styles').fadeOut("fast", function() {
        	selections[step - 1] = questions[step -1].options[0].id;
        	
            step++;
            
            if (step <= MAX) {
            	$('#quizStep #leftStyle').attr( 'src', questions[step -1].options[0].url );
        		$('#quizStep #rightStyle').attr( 'src', questions[step -1].options[1].url );
        		$('#quizStep #leftStyle').attr( 'alt', questions[step -1].options[0].desc );
        		$('#quizStep #rightStyle').attr( 'alt', questions[step -1].options[1].desc );
        		$("#stepInfo").html(step + " of " + MAX);
        		$('#quizResult .leftMask').addClass("hover");
        		//$('#tip').text(questions[step -1].options[0].desc);
        		//$('#tip').show();  
            }
            
            setSteps(step);            
            afterSelect(step);
        });
    });
    //select right style
    $('#quizStep .rightMask').click(function() { 
    	$('#quizResult .leftMask').removeClass("hover").addClass("unhover");
        //$('#tip').hide();   	
        $('#quizStep .styles').fadeOut("fast", function() {
        	selections[step - 1] = questions[step -1].options[1].id;
        
            step++;
            if (step <= MAX) {
            	$('#quizStep #leftStyle').attr( 'src', questions[step -1].options[0].url );
        		$('#quizStep #rightStyle').attr( 'src', questions[step -1].options[1].url );
        		$('#quizStep #leftStyle').attr( 'alt', questions[step -1].options[0].desc );
        		$('#quizStep #rightStyle').attr( 'alt', questions[step -1].options[1].desc );
        		$("#stepInfo").html(step + " of " + MAX);
        		$('#quizResult .leftMask').addClass("hover");
        		//$('#tip').text(questions[step -1].options[1].desc);
        		//$('#tip').show();  	
            }
            
            setSteps(step);
            
            afterSelect(step);
        });
    });



    //utility: setSteps progress
    function setSteps(idx) {
        $('#info .steps li').each(function(i) {
            if (i < idx) {
                $(this).addClass("done");
            }
        });
        if(idx<=MAX) $('#info #stepInfo').text(idx+" of "+MAX)
    }

})
