// JavaScript Document
var isAnimStopped = true;
var isHideStopped = true;
var genreAnimStopped = true;
var autoRotate = 'end';

var initialPosition = 0, startDragging = false, documentProperties = [];
var iBox, iBoxPositions, leftEdge, rightEdge, topEdge, bottomEdge;
var initialPosition = 0;
var sign;
var currentScreen = 1;
var tableLeftPosition, lf="0px", rt="0px";

function test(){
    if ('end' !== autoRotate) {
        var elm = $(".app_next").parent()
								.parent()
								.find("div.carousel_clip")
								.find("div.icarousel")
								.find("table");
        var verticalId = $(".app_next").parent()
									   .parent()
									   .find("div.carousel_clip");
        var wdth = parseInt(verticalId.css('width'));

        if ((Math.abs(parseInt(elm.css('left'))) + 334 + 160) >= elm[0].offsetWidth) {
            elm.css({
                left: wdth + "px"
            });
            //slideCarousel(elm, '-');
        }

        if (isAnimStopped) {
            slideAutoCarousel(elm, '-', wdth);
        }

        var tst = setTimeout("test()", 2000);
    } else {
        clearTimeout(tst);
    }
}

function swapContent(app_id){
    $.ajax({
        url: "data/data.php",
		data: "app_id="+app_id,
		type: "POST",
		dataType: 'json',
        success: function(appData){
			//alert("Hi1="+ appData);
            var index = 'app' + app_id;
            
            $('.app_info').html(appData[index].description);
            $('.btn_user_act').attr("href", appData[index].url);
            $('#glass').removeClass();
            $('#glass').addClass(appData[index].orientation);
            $('#app_title').text(appData[index].name);
            $('#app_genre').text('Genre: ' + appData[index].genre);
            $('#app_release_date').text('Date released: ' + appData[index].date);
            $('#app_price').text(appData[index].price);
            $('#icarousel table').css({
                left: '0px'
            });
            $('#icarousel table tbody tr').html(appData[index].images);
            iBoxPositions = findPositions(iBox);
			leftEdge = parseInt(iBoxPositions.left)+15;
			rightEdge = parseInt(iBoxPositions.right)-15;
			topEdge = parseInt(iBoxPositions.top)+15;
			bottomEdge = parseInt(iBoxPositions.bottom)-15;	
			
            test();
        }
    });
}
function slideAutoCarousel(elm, sign, wdth){
  
    var no = parseInt(elm.css('left'));
   
    
    isAnimStopped = false;
    if (sign == '+') {
        no += wdth;
		currentScreen = currentScreen-1;
    } else {
        no -= wdth;
		currentScreen = currentScreen+1;
    }
    elm.animate({
        left: no
    }, 600, 'easeInQuad', function(){
        isAnimStopped = true;
    });
}
function slideCarousel(elm, sign, wdth){
		   
    var no = elm.css('left');	
	no = parseInt(no);	
	wdth = parseInt(wdth);
		
    isAnimStopped = false;

    if (sign == '-') {		
		var dragg = currentScreen * wdth;
		elm.animate({
			left: "-"+dragg+"px"
		}, 900, 'easeInQuad', function(){
			isAnimStopped = true;
			currentScreen = currentScreen+1;		
		});						
    } else {		
        var tmp = parseInt((currentScreen-1) * wdth);
		var dragg = tmp - wdth;
		elm.animate({
			left: "-"+dragg+"px"
		}, 600, 'easeInQuad', function(){
			isAnimStopped = true;
			currentScreen = currentScreen-1;		
		});					
    }
	   
}
findLeftRight=function(e,element){
	if (startDragging) {
		var cursorPositionX = e.clientX;
	    var cursorPositionY = e.clientY;
		
		var diff = initialPosition-cursorPositionX;
		 lf = tableLeftPosition-diff;
		
		var diff2 = initialPosition-cursorPositionX;
		 rt = tableLeftPosition-diff;
		
		
		 if (cursorPositionX <= rightEdge && cursorPositionX >= leftEdge &&
		     cursorPositionY <= bottomEdge && cursorPositionY >= topEdge) {
			
			var leftPosition = parseInt(initialPosition-cursorPositionX)+"px";
			var rightPosition = parseInt(cursorPositionX - initialPosition)+"px";	
			
		 	 if(initialPosition - cursorPositionX > 0){			 		   	 			
				//$(element).css({left : lf+"px"});	
				document.getElementById('tableId').style.left = lf+"px";
				sign = '-';
			 } else {
			 	//$(element).css({left : rt+"px"});
				document.getElementById('tableId').style.left = lf+"px";
				sign = '+';
			 }
		 } else {
		 	release(e,element);
		 }
	}
}

release = function(e,element){	
	if (startDragging) {
	    if (!e) {
	        e = window.event;
	    }		
	}
	var el = $('#carousel_clip');
	var originalWidth = el.css('width');
	originalWidth = originalWidth.replace("px","");
	var elm = $('#carousel_clip').find("#icarousel").find('table');
	var totalCells = $('#carousel_clip').find("#icarousel table").find('td');
		
	var cursorPositionX = e.clientX;	
	
	if(initialPosition - cursorPositionX > 0) {
		sign = '-';
	} else {
		sign = '+';
	}	
	
	if(currentScreen==1 && sign == '+') {
		elm.animate({left: "0px"},600);
	} else if(currentScreen==totalCells.length && sign == '-') { 
		var revertPos = (currentScreen - 1) * originalWidth;
		elm.animate({left: "-"+revertPos+"px"},600);
	} else {
		slideCarousel(elm,sign,originalWidth);
	}

	startDragging = false;
	initialPosition = 0;

	if (document.body.style.MozUserSelect) {
		document.body.style.MozUserSelect = documentProperties[0];
	}
	document.unselectable;
	
}
getInitialPosition = function(e){
    if (!e) {
        e = window.event;
    }

    initialPosition = e.clientX;	
	startDragging = true;
	var carouselTable = $('#carousel_clip').find('#icarousel').find("table");		
	tableLeftPosition = carouselTable.css('left');
	tableLeftPosition = parseInt(tableLeftPosition);
	
	
	e.preventDefault();
	if (document.body.style.MozUserSelect) {
 	    document.body.style.MozUserSelect = false;
	}
	document.unselectable;
}
findPositions = function(node){
    if (!node) {
        node = document.body;
    }

    var top = new Number(), left = new Number(), bottom = new Number(), right = new Number(), region = new Number();

    if (typeof(node.offsetParent) != 'undefined') {
        bottom = node.offsetHeight;
        right = node.offsetWidth;
		
        for (var top = 0, left = 0; node; node = node.offsetParent) {
            left += node.offsetLeft;
            top += node.offsetTop;
        }
		
        bottom += top;
        right += left;
    }

    region = (top + bottom) * (left + right);

    return {
        top: top,
        left: left,
        bottom: bottom,
        right: right,
        region: region
    };
}

$(document).ready(function(){
	var numofIcons=$('#numofIcons').val();
	//alert("numofIcons="+numofIcons);
	var numApp;
		numApp = numofIcons * 100;
		$('#apps').css('width', numApp);
	/*var numApp;
		numApp = 3 * 100;
		$('#apps').css('width', numApp);*/
		//jay starting here
    //swapContent(0);
	 //swapContent(1);
    test();   
    iBox = document.getElementById('carousel_clip');
	
    /* Taken from Document.ready*/
    $("#apps li").append("<span class='spotlight'></span>");
    $("#apps li").append("<span class='arrow'></span>");
    
    $("#apps li").hover(function(){
        $(this).find(".spotlight").animate({
            opacity: "show",
            top: "14"
        }, "slow");
        var hoverText = $(this).attr("title");
        $(this).find(".spotlight").text(hoverText);
    }, function(){
        $(this).find(".spotlight").animate({
            opacity: "hide",
            top: "0"
        }, "fast");
    });
    
    $("#iphone").hover(function(){
        $(this).find(".controls").animate({
            opacity: "show",
            bottom: "75"
        }, "slow");
    }, function(){
        $(this).find(".controls").animate({
            /*opacity: "hide",*/
			opacity: "show",
            bottom: "75"
        }, "fast");
    });
    
    $(".app_pause").click(function(){
    
        var stat = $("#myh1").val();
        
        if (stat == 'end') {
            autoRotate = 'start';
            $("#myh1").val('start');
        } else {
            autoRotate = 'end';
            $("#myh1").val('end');
        }  
        
        test();
        
    });
    $(".new").click(function(){
        autoRotate = 'end';
        $("#myh1").val('end');
        //alert(autoRotate);		
        currentScreen = 1;		
		 test();
    });
    $(".free").click(function(){
        autoRotate = 'end';
        $("#myh1").val('end');
        //alert(autoRotate);
		currentScreen = 1;			
        test();
    });
    
    
    $('#apps li').click(function(){
        $('#apps li').removeClass('selected');
        $('#apps li').find(".arrow").animate({
            opacity: "hide",
            bottom: "10"
        }, "fast");
        $(this).addClass('selected');
        $(this).find(".arrow").animate({
            opacity: "show",
            bottom: "20"
        }, "fast");
        $('#icarousel').css('left', '0');
        return false;
    });  

    $('.app_prev').click(function(){    
        var elm = $(this).parent().parent().find("div.carousel_clip").find("div.icarousel").find("table");
        var verticalId = $(this).parent().parent().find("div.carousel_clip");
        var wdth = parseInt(verticalId.css('width'));
        var no = parseInt(elm.css('left'));
        if (no == 0) {
            return false;
        }
        if (isAnimStopped) {
            slideAutoCarousel(elm, '+', wdth);
        }
    });

    $('.app_next').click(function(){
        var elm = $(this).parent().parent().find("div.carousel_clip").find("div.icarousel").find("table");
        var verticalId = $(this).parent().parent().find("div.carousel_clip");
        var wdth = parseInt(verticalId.css('width'));
        if ((Math.abs(parseInt(elm.css('left'))) + 334 + 160) >= elm[0].offsetWidth) {
            return false;
        }
        if (isAnimStopped) {
            slideAutoCarousel(elm, '-', wdth);
        }
    });

    iBoxPositions = findPositions(iBox);
	leftEdge = parseInt(iBoxPositions.left)+15;
	rightEdge = parseInt(iBoxPositions.right)-15;
	topEdge = parseInt(iBoxPositions.top)+15;
	bottomEdge = parseInt(iBoxPositions.bottom)-15;
	
	var container = $("#carousel_clip");
	var content = $("#tableId");
	
	$('#carousel_clip').bind("mousedown", function(e){
		getInitialPosition(e);
	});

	$('#carousel_clip').bind("mousemove", function(e){
		findLeftRight(e,content);
	});

	$('#carousel_clip').bind("mouseup", function(e){
		release(e,content);
	});

});


