﻿var hoverTime = 500;
var hoverIt = "";
var currTr = "";
var nextSrc = "";
var overStatus = 0;
var flipHeaderExists = false;
var flipImgArr = [];
function showAddress(obj,cmd) {
	if(cmd=="show") {
		$(obj).find('div.addressInfo').slideDown('fast');
	} else {
		$(obj).find('div.addressInfo').slideUp('fast');
	}
}

$(function() {
	if($("#cm_network_search").length>0) {
		cm_network_search('init');
	}	
	
	
	if($(".cm_result").length>0) {
		
		// map over
		$("li.summary").hover(
			function() {
				var tmpClass = $(this).attr('class').replace('summary ','');
				$("#cm_dkmap div.spotContainer img[class!=" + tmpClass + "]").hide();
			},
			function() {
				$("#cm_dkmap div.spotContainer img").show();
			}
		);
		
		var spotDelay = Math.floor(300/$(".spotContainer img").length);
		showSpot(0,spotDelay);
		
		$(".cm_result table tr:gt(0)").hover(
			function() {
				$(this).css('backgroundColor','#dae9b1');
				currTr = $(this);
				hoverIt = setTimeout("showAddress(currTr,'show')", hoverTime);
			},
			function() {
				clearTimeout(hoverIt);
				$(this).css('backgroundColor','#fff');
				showAddress($(this),'')
			}
		);
		
		jQuery.each($(".cm_result table"), function() {
		
			var nuOfColumns = $(this).find('tr:first th').length;
			var nuOfRows = $(this).find('tr:gt(0)').length;
			var bottomTotals = [];
			var nextIndex = 0;

			// find index of column where first product is
			var firstProduct = parseInt($(this).find("tr:eq(0) th[class!='product']").length-1);
			
			jQuery.each($(this).find('tr:gt(0)'), function() {
				var tmpTotal = 0;
				jQuery.each($(this).find('td:gt(' + firstProduct + ')'), function() { 
					tmpTotal += parseInt($(this).html()); 
				});
				if(tmpTotal==0) $(this).remove();
			});
			
			for(i=0;i<nuOfColumns; i++) {
				if($(this).find('tr:first th:eq(' +  i + ')').html()==null) {
					$(this).removeCol(i);
				} else {
					if(i>0) {
						bottomTotals[nextIndex] = 0;
						nextIndex++
					}
				}
			}

			var currTotal = 0;
			var currValue = 0;
			
			for(var i=0; i<bottomTotals.length; i++) {
				currTotal = 0;
				
				jQuery.each($(this).find('tr td[class=c' + i + ']'), function() {
					currValue = $(this).html();
					if(currValue==null) { currValue = 0; }
					if(currValue.length>0) {
						currValue = (isNaN(currValue)) ? 0 : parseInt(currValue);
					} else {
						currValue = 0;
					}
					currTotal += currValue;					
				});
				bottomTotals[i] = currTotal;
			}	
			//alert(bottomTotals.toString());
			var columnsToRemove = [];
			var columnsToRemoveCounter = 0;				
			for(var i=0; i<bottomTotals.length; i++) {
				if(parseInt(bottomTotals[i])==0) {
					columnsToRemove[columnsToRemoveCounter] = i+1;
					columnsToRemoveCounter++			
				}
			}
			
			
			var newRow = "<tr><td class=\"bottomTotal left\">Samlet</td>";
			for(var i=0; i<bottomTotals.length; i++) {
				tmpClass = (i==3) ? " strong" : "";
				newRow = newRow + "<td class=\"bottomTotal" + tmpClass + "\">" + bottomTotals[i] + "</td>";
			}
			$(this).append(newRow);

			columnsToRemove.reverse();
			for(var i=0; i<columnsToRemove.length; i++) {
				$(this).removeCol(columnsToRemove[i]+1);
			}					
			
			// remove all lines with only 0's
			// jQuery.each($(this).find('tr:gt(0)'), function() {
				// var tmpTotal = 0;
				// jQuery.each($(this).find('td:gt(0)'), function() { tmpTotal += $(this).html(); });
				// if(tmpTotal==0) $(this).remove();
			// });
			
	
			//$(this).removeCol(firstProduct+1);
			
			if($(this).find("tr:eq(1) td.c0,td.c1,td.c2").length==1) {
				//$(this).find("td.c3").remove();
				$(this).removeCol(3);
			} else {
				// $(this).find("td.c3").css('fontWeight','bold');
			}
		});
	}
	
	if($("#caseHolder").length>0) {
		cm_showCase();
	}
	if($("a.caseLink").length>0) {
		$("a.caseLink").bind('click', function() {
			var tmpId = $(this).attr('rel');
			cm_openCase(tmpId);
			return false;
		});		
	}
	
	if($("#form_login").length>0) {
		build_login_form();	
	}	
	
	if($("ul.leftMenu").length>0) {
		$("#showMoreCases").bind('click', function() {
			$(this).parent('li:first').find('ul:first').toggle();
		});
		if($("ul.leftMenu li.active").length>0) $("#showMoreCases").parent('li:first').find('ul:first').css('display','block');
	}	
	
	if($("#flipBox").length>0) {

		//$("#inner_bottom").hide();		
		// $("#nextSrc").css({
			// 'position' : 'absolute',
			// 'top' : '-1000px',
			// 'left' : '-1000px'
		
		// });
		$("#flipBox").css('height',$("#flipBox img").height()+'px');
		$("#flipBox img:first").css({'zIndex' : '10', 'position' : 'absolute', 'top' : '65px', 'left' : '0px'}).attr('title','');
		$("#nextSrc img").clone(true).appendTo("#flipBox");
		$("#flipBox img:last").css({'zIndex' : '9', 'position' : 'absolute', 'top' : '65px', 'left' : '0px'}).attr('title','');
		$(".flipContainer").hover(
			function(){
				if(overStatus==1) {
					//readyToNext = false;
					//isOver = true;
					$("#flipBox img:first").animate({ 'opacity' : 0 },{ 'duration' : 1000, complete: function() {
						$("#textBox").animate({
							'opacity' : 0
						},{
							duration: 500,
							complete: function() {
								var newTxt = $("#nextTxt").html();
								var oldTxt = $("#textBox").html();
								$("#textBox").html(newTxt);
								$("#nextTxt").html(oldTxt);
								$("#textBox").animate({ 'opacity' : 1 },{ duration: 300, complete: function() { overStatus=2; } });
								//readyToNext = true;
								//overStatus = 1;
							}
						
						});				
					}});
					
				}
			},
			function() {
				//if(readyToNext) {
					//readyToNext = false;
					if(overStatus==2) {
						$("#flipBox img:first").animate({ 'opacity' : 1 },{ 'duration' : 1000, complete: function() {
							$("#textBox").animate({
								'opacity' : 0
							},{
								duration: 500,
								complete: function() {
									var newTxt = $("#nextTxt").html();
									var oldTxt = $("#textBox").html();
									$("#textBox").html(newTxt);
									$("#nextTxt").html(oldTxt);
									$("#textBox").animate({ 'opacity' : 1 },{ duration: 300, complete: function() { overStatus=1; } });
									// readyToNext = true;
									// overStatus = 0;
								}							
							});				
						}});
					}
				//}				
			}
		);
		
		overStatus = 1;
	}
	
});
var isOver = false;
var readyToNext = true;
function switchOverStatus() {
	readyToNext = (readyToNext) ? false : true;
	overStatus = (overStatus==1) ? 0 : 1;
}

function flipIt() {
	$("#flipBox").flip({
		direction: 'lr',
		color: '#fff',
		speed: 550,
		content: $("#nextSrc"),
		onEnd: function() {
			overStatus = (overStatus==0) ? 1 : 0;
			$("#tst").html(overStatus + " - " + readyToNext);
			$("#headerClone").hide();
			$("#flipBox img").css({ 'opacity' : 0, 'display' : 'block' }).animate({ 'opacity' : 1 },{duration: 500}); 
				$("#textBox").animate({
					'opacity' : 0
				},{
					duration: 500,
					complete: function() {
						var newTxt = $("#nextTxt").html();
						var oldTxt = $("#textBox").html();
						$("#textBox").html(newTxt);
						$("#nextTxt").html(oldTxt);
						$("#textBox").animate({ 'opacity' : 1 },{ duration: 500 });
						$("#headerClone").hide(); 						
						readyToNext = (readyToNext) ? false : true;
						$("#tst").html(overStatus + " - " + readyToNext);
					}
				
				});						
		}
	});			
}

function showSpot(index,spotDelay) {
	if($(".spotContainer img:eq(" + index + ")").length>0) {
		$(".spotContainer img:eq(" + index + ")").show();
		index++
		setTimeout("showSpot(" + index + "," + spotDelay + ")",spotDelay);
	}
}

$.fn.removeCol = function(col){
    // Make sure col has value
    if(!col){ col = 1; }
    $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
};

function cm_network_search(cmd) {
	switch(cmd) {
		case "init":
			$("#cm_network_search input[type='checkbox']").bind('click', function() {
				if(!$(this).hasClass('allSelect')) {
					var isAnySelected = false;
					jQuery.each($(this).parent('td').find('input:gt(0)'), function() {
						isAnySelected = $(this).attr('checked') ? true : isAnySelected;
					});
					if(isAnySelected) {
						$(this).parent('td').find('input:eq(0)').attr('checked',false);
					} else {
						$(this).parent('td').find('input:eq(0)').attr('checked',true);
					}
				}			
			});
			$("#cm_network_search input.allSelect").bind('click', function() {
				if($(this).attr('checked')) {
					$(this).parent('td').find('input:gt(0)').attr('checked',false);
				}
			});
			$("#cm_network_btn_search").bind('click', function() {
				cm_network_search('search');
			});
			$("#cm_network_search form").bind('submit', function() {
				if($("#cm_network_search td.network input[class='allSelect']").attr('checked')) {
					$("#cm_network_search td.network input[name='network']").attr('checked',true);
				}
				if($("#cm_network_search td.product input[class='allSelect']").attr('checked')) {
					$("#cm_network_search td.product input[name='product']").attr('checked',true);
				}
			});
		break;
	}
}

var currentSlide = 0;
var slideContentArr = [];

function cm_openCase(caseId) {
	$.ajax({
		type: "POST",
		url: "/inc/modules/citrus/cases/ajax.asp",
		data: "cmd=getCase&case=" + caseId,
		success: function(msg){ 
			$("body").append(msg);
			cm_showCase();
		}
	 });
}

function cm_closeCase() {

	$("#caseHolder").animate({
		'opacity' : 0
		},{
		duration : 100,
		complete: function() {

			$("#caseModal").animate({
				'opacity' : 0
				},{
				duration : 100,
				complete: function() {					
					$("#caseHolder").remove();
					$("#caseModal").remove();
					currentSlide = 0;
					slideContentArr = [];					
					$(document).unbind('keydown');
					return false;
				}
			})		
			
		}
	})
}

function cm_showCase() {
	var caseModal = $("#caseModal").clone();
	var caseHolder = $("#caseHolder").clone();
	$("#caseModal").remove();
	$("#caseHolder").remove();
	$("body").append(caseHolder).append(caseModal);
	
	cm_case_slide_getContent(0);
	
	$("#caseModal").css({'opacity' : 0, 'display' : 'block'})
	.bind('click', function() { cm_closeCase(); })
	.animate({ 'opacity' : 0.7 },{ duration: 200, complete: function() {
		$("#caseHolder ul.slideContainer li:eq(" + currentSlide + ")").css('display','block');
		// continue with init
		$("#caseHolder")
		.css({ 
			'top' : Math.floor(($("body").height()-600)/2) + 'px',
			'left' : Math.floor(($("body").width()-735)/2) + 'px',
			'opacity' : 0,
			'display' : 'block'
		})
		.animate({ 'opacity' : 1 },{ duration: 200 });
		$("#caseHolder div.topNav div.left").bind('click', function() {
			cm_case_previousSlide();
		});
		$("#caseHolder div.topNav div.right").bind('click', function() {
			cm_case_nextSlide();
		});
		$(document).bind('keydown', function(event) {
			switch(event.keyCode) {
				case 27:
					//ESC
					cm_closeCase();
				break;
				case 39:
					//right
					cm_case_nextSlide();
				break;
				case 37:
					//left
					cm_case_previousSlide();
				break;
			}
		});
	
	} });
	
}

function cm_case_slide_getContent(slideNr) {
	
	if(slideContentArr[slideNr]) {
		$("#caseHolder ul.slideContainer li:eq(" + slideNr + ")").html(slideContentArr[slideNr]);
		return "ok";
	} else {
		var slideId = $("#caseHolder ul.slideContainer li:eq(" + slideNr + ")").attr('id');
		
		if(slideId!="") {
			slideId = slideId.replace("slide_","");
			$.ajax({
				type: "POST",
				url: "/inc/modules/citrus/cases/ajax.asp",
				data: "cmd=getContent&slide=" + slideId,
				success: function(msg){ 
					if(msg.length==0) {
						slideContentArr[slideNr] = "<p></p>";
					} else {
						slideContentArr[slideNr] = msg;
					}
					$("#caseHolder ul.slideContainer li:eq(" + slideNr + ")").html(msg);
					if($("img.caseImages").length>0) {
						jQuery.each($("img.caseImages"), function() {
							var tmpSrc = $(this).attr('src');
							$(this).wrap("<a href=\"" + tmpSrc + "\" class=\"caseImages\"></a>");			
						});
						$("a.caseImages").colorbox();
					}					
				}
			 });
			return "ok";		
		}
	}
	
}

function cm_case_nextSlide() {
	
	var activeSlide = $("#caseHolder ul.slideContainer li:eq(" + (currentSlide) + ")");
	
	if($("#caseHolder ul.slideContainer li:eq(" + (currentSlide+1) + ")").length<=0) {
		var nextSlide = $("#caseHolder ul.slideContainer li:eq(0)");
		currentSlide = 0;
	} else {
		var nextSlide = $("#caseHolder ul.slideContainer li:eq(" + (currentSlide+1) + ")");
		currentSlide++;
	}
	
	$(nextSlide).css({ 'left': '735px', 'display' : 'block' });
	
	if(cm_case_slide_getContent(currentSlide) == "ok") {
		$(activeSlide).animate({
			'left' : '-735px'
			},{
			duration: 500,
			complete: function() {
				$(activeSlide).html('');
				$(activeSlide).css('zIndex',currentSlide);
			}
		});

		$(nextSlide).animate({
			'left' : '0px'
			},{
			duration: 500,
			complete: function() {
				$(nextSlide).css('zIndex','1000');		
			}
		});
			
		$("#caseHolder div.bottomNav span:first").html(currentSlide+1);
	}
	
}

function cm_case_previousSlide() {
	var activeSlide = $("#caseHolder ul.slideContainer li:eq(" + (currentSlide) + ")");
	if($("#caseHolder ul.slideContainer li:eq(" + (currentSlide-1) + ")").length<=0||parseInt(currentSlide-1)<0) {
		var nextSlide = $("#caseHolder ul.slideContainer li:eq(" + parseInt($("#caseHolder ul.slideContainer li").length-1) + ")");
		currentSlide = parseInt($("#caseHolder ul.slideContainer li").length-1);
	} else {
		var nextSlide = $("#caseHolder ul.slideContainer li:eq(" + (currentSlide-1) + ")");
		currentSlide = currentSlide - 1;
	}
	
	$(nextSlide).css({ 'left': '-735px', 'display' : 'block' });

	if(cm_case_slide_getContent(currentSlide) == "ok") {
		$(activeSlide).animate({
			'left' : '735px'
			},{
			duration: 500,
			complete: function() {
				$(activeSlide).html('');
			}		
		});

		$(nextSlide).animate({
			'left' : '0px'
			},{
			duration: 500
		});
		
		$("#caseHolder div.bottomNav span:first").html(currentSlide+1);
	}
}



function build_login_form() {
	
	$("#form_login").append(
		"<input type=\"text\" id=\"login_username\" name=\"ocms_usr\" />" + 
		"<input type=\"text\" id=\"login_passwordTxt\" />" +
		"<input type=\"password\" id=\"login_password\" name=\"ocms_pwd\" />" +
		"<input class=\"btn\" type=\"submit\" id=\"login_submit\" value=\"Login &raquo;\" />"
	);
	// $("#login_submit").hover(
		// function() {
			// $(this).css("background","url(/ocms/gfx/login_btn_submit_over.png) top left no-repeat");
		// },
		// function() {
			// $(this).css("background","transparent");
		// }
	// )
	$("#form_login_container").css("display","block");
	$("#login_username")
	.val('Brugernavn')
	.bind('focus', function() {
		if($(this).val()=="Brugernavn") $(this).val('');
	})
	.bind('blur', function() {
		if($(this).val()=="") $(this).val('Brugernavn');
	});
	
	$("#login_passwordTxt")
	.val('Password')
	.bind('focus', function() {
		$(this).hide();
		$("#login_password").focus();
	});
	
	$("#login_password")
	.bind('blur', function() {
		if($(this).val().length==0) {
			$("#login_passwordTxt").show(); 
		}
	});	
}

function clean_string(str) {
	if(str!="") {
		var tmp = str;
    var regExp = new RegExp("[^0-9-_a-zA-Z@\.]","gi");
    tmp = tmp.replace(regExp,"");		
		return tmp;
	}
}


function validate_login() {
	var usr = document.getElementById("login_username");
	var pwd = document.getElementById("login_password");
	if(usr.value != "" && pwd.value.length > 0) {
		usr.value = clean_string(usr.value);
		return true;
	} else { 
		return false;
	}
}

function readCaseTeaser(caseId) {
	if($("#cmct_" + caseId).length>0) {
		var isHidden = ($("#cmct_" + caseId).find('div').css('display')=='none') ? true : false;
		if(isHidden) {
			$("#cmct_" + caseId).find('div').slideDown('normal');
		} else {
			$("#cmct_" + caseId).find('div').slideUp('normal');
		}
		
	}
}


function toggleDetails() {
	if($("#networkDetails").attr('checked')) {
		$("div.addressInfo").show();
	} else {
		$("div.addressInfo").hide();
	}
}

function toggleInfo(codeName) {
	if($("#network_description_" + codeName).length>0) {
		$("#networkInfo").html($("#network_description_" + codeName).html()).css({ 'width' : '100%'});;
		$("#networkInfoTable").css({'display':'table', 'width' : '356px'});
	}
}

function txtCounter(obj,counterTarget,maxLength) {
	var currLength = $("#" + obj).val().length;
	if(currLength>maxLength) {
		$("#" + obj).val($("#" + obj).val().substring(0,maxLength));
		$("#" + counterTarget).find('span:first').html(maxLength);
	} else {
		$("#" + counterTarget).find('span:first').html(currLength);
	}
}


function validateFakForm() {
	if($('#file1').val().length==0) { 
		alert('Husk at vedhæfte faktura!')
		return false
	} else {
		var theForm,student_firstName,student_lastName,student_age,student_edu,student_school,student_q1,student_q2,what_customer;
		
		student_firstName = "";
		student_lastName = "";
		student_age = "";
		student_edu = "";
		student_school = "";
		student_q1 = "";
		student_q2 = "";
		what_customer = "";
		
		theForm = $("#fakForm");
		if(theForm.find('input[name=student_firstName]').length>1) {
			// array
			for(var i=0; i<theForm.find('input[name=student_firstName]').length; i++) {
				student_firstName = student_firstName + "\"\",\"\"" + theForm.find('input[name=student_firstName]:eq(' + i + ')').val();
				student_lastName = student_lastName + "\"\",\"\"" + theForm.find('input[name=student_lastName]:eq(' + i + ')').val();
				student_age = student_age + "\"\",\"\"" + theForm.find('input[name=student_age]:eq(' + i + ')').val();
				student_edu = student_edu + "\"\",\"\"" + theForm.find('input[name=student_edu]:eq(' + i + ')').val();
				student_school = student_school + "\"\",\"\"" + theForm.find('input[name=student_school]:eq(' + i + ')').val();
				student_q1 = student_q1 + "\"\",\"\"" + theForm.find('textarea[name=student_q1]:eq(' + i + ')').val();
				student_q2 = student_q2 + "\"\",\"\"" + theForm.find('textarea[name=student_q2]:eq(' + i + ')').val();
				what_customer = what_customer + "\"\",\"\"" + theForm.find('input[name=what_customer]:eq(' + i + ')').val();
			}
			student_firstName = student_firstName.substring(5,student_firstName.length);
			student_lastName = student_lastName.substring(5,student_lastName.length);
			student_age = student_age.substring(5,student_age.length);
			student_edu = student_edu.substring(5,student_edu.length);
			student_school = student_school.substring(5,student_school.length);
			student_q1 = student_q1.substring(5,student_q1.length);
			student_q2 = student_q2.substring(5,student_q2.length);
			what_customer = what_customer.substring(5,what_customer.length);
			theForm.find('div[id=interview]:gt(0)').remove();
			
			theForm.find('input[name=student_firstName]').val(student_firstName);
			theForm.find('input[name=student_lastName]').val(student_lastName);
			theForm.find('input[name=student_age]').val(student_age);
			theForm.find('input[name=student_edu]').val(student_edu);
			theForm.find('input[name=student_school]').val(student_school);
			theForm.find('textarea[name=student_q1]').val(student_q1);
			theForm.find('textarea[name=student_q2]').val(student_q2);
			theForm.find('input[name=what_customer]').val(what_customer);
			return true
		}
		
		return true
	}
}

function addInterview() {
	var clone = $('#interview').clone();
	clone.find('input,textarea').val('');
	$('#interviews').append(clone);
}