/**
 * @author LBi
 * @namespace telenor.main
 */

/* Main JS file
 * Telenor
 * 
 */

/* ========================  ======================== */
/* ------------------------  ------------------------ */
/* ........................  ........................ */



/* ======================== General functions ======================== */



/* ------------------------ set global namespace object ------------------------ */
/** @id globalNamespace 
*/

var telenor = {};


/* ------------------------ get data from classname ------------------------ */
/** @id classData 
*/

jQuery.fn.classData = function(dataType){
	var classString = false;

	this.each(function(){ 
		classString = this.className.split(' ');
		for (var i=0, il=classString.length; i<il; i++) {
			if (classString[i].indexOf('data_'+dataType) >= 0) {
				classString = classString[i].replace('data_'+dataType+'(','').replace(')','');
			}
		}
	});

	return classString;
};


/* ------------------------ font resize detection ------------------------ */
/** @id chk_fontResize 
*/
function chk_fontResize(chkObj) {
	if(typeof(chkObj) === 'undefined') {
		return;
	}
	
	if (!this.prevVal) {
		this.prevVal = chkObj.offsetHeight;
	}
	if (chkObj.offsetHeight != this.prevVal) {
		this.prevVal = chkObj.offsetHeight;
		$(window).trigger('fontResize');
	}
}

$(function(){ chk_fontResize.obj = $('#anchor_content')[0]; setInterval("chk_fontResize(chk_fontResize.obj)", 250); }); // on page load



/* ------------------------ respectHeight ------------------------ */
/** @id jQuery.fn.respectHeight  
*/
jQuery.fn.respectHeight = function(authority,maintainHeight){
	var highest;
	if (authority) { // check that element
		highest = jQuery(authority).height();
	}
	else { // make array, check all, find biggest
		highest = new Array();
		var intPadding = 0;
		if(!maintainHeight && telenor.ie6) { // if downsizing font
			this.each(function(){ jQuery(this).height('auto'); });
		} else if (!maintainHeight) {
			this.each(function(){ 
			jQuery(this).css('min-height',0); });
			
		}
		this.each(function(i){ 
			if($.browser.safari) { 
			// Verkar inte beh�vas - sabbar layout / Pelle 081204
			// intPadding = parseInt($(this).css("padding-top").replace(/[^0-9.,]/g,"")) + parseInt($(this).css("padding-bottom").replace(/[^0-9.,]/g,""));
			}
			highest[i] = parseInt(jQuery(this).height()+intPadding); 
		});
		highest.sort(function(a, b){return b - a});
		highest = highest[0];
	}
	
	// set all from biggest
	if (telenor.ie6) {
		this.each(function(){ 
			jQuery(this).height(highest);
		});
	} else {
		this.each(function(){ jQuery(this).css('min-height',highest+'px'); });
	}
};


/* ------------------------ convert object tags to iframes (for IE) ------------------------ */
/** @id ie_iFrameBuilder  
*/
function ie_iFrameBuilder(scope) {
	$('.replace_iframe',scope).each(function(){
		var iframeId, iframeName, iframeClassName;
		
		if (this.id != '') {
			iframeId = ' id="' + $(this).attr('id') + '"';
		}
		
		if (this.name != '') {
			iframeName = ' name="' + $(this).attr('name') + '"';
		}
		
		iframeClassName = $(this).attr('class');
		iframeClassName = iframeClassName.replace('replace_iframe', '');
		if (iframeClassName != '') {
			iframeClassName = ' class="' + iframeClassName + '"';
		}
		
		var iFrameString = '<iframe frameborder="0"' + iframeId + iframeName + iframeClassName + ' src="' + $(this).attr('data') + '">' + $(this).html() + '</iframe>';
		$(this).replaceWith(iFrameString);
	});
}

/* ------------------------ Force IE6 to re-render element ------------------------ */
/** @id ie6forceRendering  
*/
function ie6forceRendering(selector) {
	//$(selector).css('height','1%');
	//$(selector).css('height','auto');
}

/* ------------------------ Apply extra wrapping for IE6 on RCB bottom corners ------------------------ */
/** @id ie6FixBottomCorners  
*/
function ie6FixBottomCorners() {
	$('div.rcb:not(.no-corner-fix) b.sW').each(function(){
		var parentWidth = 0;
		var myParent = $(this).parent();
		var xtrabottom = myParent.css('margin-bottom');
		if (xtrabottom != '' && xtrabottom) { $(this).css('bottom', xtrabottom).next('b').css('bottom', xtrabottom); }

		var parentPadLeft = myParent.css('padding-left');
		var parentPadRight = myParent.css('padding-right');
		if (parentPadLeft != '0px') { 
			parentWidth = parentWidth + parseInt(parentPadLeft);
		}
		if (parentPadRight != '0px') { parentWidth = parentWidth + parseInt(parentPadRight); }
		
		myParent.wrap('<div class="sys_ieRcbWrap" style="float:'+myParent.css('float')+';width:'+(myParent.width()+parentWidth)+'px;"></div>');
		$(this).parents('.sys_ieRcbWrap').eq(0).append('<div class="sys_ieRcb" style="position:relative;z-index:400;clear:both;margin-left:'+myParent.css('margin-left')+';margin-right:'+myParent.css('margin-right')+';width:'+(myParent.width()+parentWidth)+'px;"></div>');

		$(this).next('b').appendTo($(this).parents('.sys_ieRcbWrap').eq(0).children('.sys_ieRcb'));
		$(this).appendTo($(this).parents('.sys_ieRcbWrap').eq(0).children('.sys_ieRcb'));
	});
	
	$('.colContBtm_sW, .colContBtm_sE').wrapAll('<div style="position: relative; z-index: 400; zoom: 1;"></div>'); 
}



/* ------------------------ IE 6 check ------------------------ */
/** @id ie6 
*/
if (($.browser.msie) && (parseInt($.browser.version) < 7)) {
	telenor.ie6 = true;
}

/* ------------------------ Pseudo-table Menu ------------------------ */
/** @id pseudoTableMenu 
*/
function pseudoTableMenu(selector,parentSelector,fixedTable){
	pseudoObjID = 'sys_pseudoTableMenu';
	var pseudoObjWidth = $(selector).parents(parentSelector).width();

	var pseudoObjItemPadding = $(selector).eq(0).css('padding-left');
	var pseudoObjItemBorder = $(selector).eq(0).css('border-left-width');
	
	var tableLayout = '';
	if (fixedTable) { tableLayout = 'table-layout: fixed;';	}
	
	$('body').append('<table class="sys_pseudoTableAlign" id="'+pseudoObjID+'" style="width:'+pseudoObjWidth+'px;'+tableLayout+'"><tr></tr></table>');
	
	$(selector).each(function(){
		$('#'+pseudoObjID+' tr').append('<td><span class="cloaked" style="padding:'+pseudoObjItemPadding+';border:'+pseudoObjItemBorder+' solid #fff">'+$(this).html()+'</span></td>');
	});
	
	var pseudoObjItemSpacing = (parseInt(pseudoObjItemPadding) * 2) + (parseInt(pseudoObjItemBorder) * 2);
	var tdCount = $('#'+pseudoObjID+' td').length;
	$('#'+pseudoObjID+' td').each(function(i){		
		if(i < (tdCount-1)) {
			$(selector).eq(i).width($(this).width() - pseudoObjItemSpacing);
		} else { /* WORKAROUND for IE8-compatibility mode (090527 by me101740)*/
			if (($.browser.msie) && (parseInt($.browser.version) == 7) && document.documentMode) {
				$(selector).eq(i).width($(this).width() - pseudoObjItemSpacing-1);
			} else {
				$(selector).eq(i).width($(this).width() - pseudoObjItemSpacing);
			}
		}
	});
	
	$('#'+pseudoObjID).remove(); // removes pseudo element in case the function is called again
}

/* ------------------------ IE6 PNG Image Alpha fix ------------------------ */
/** @id ie6PngImgFix

Changed ie6PngImgFix and ie6PngImgFixAction - 081114 by po101330 
Changed ie6PngImgFix 090922 - Pelle
*/
function ie6PngImgFix(scope,sizingMethod) {
	if (!sizingMethod) {
		sizingMethod = 'scale';
	}
	var filterStart = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod="+sizingMethod+" src='";
	var filterEnd = "');"
	
	$('img[src$=png]',scope).each(function(){
		if ($(this).attr( "complete" )) {
			if($(this).height() > 0) {
				var myParentz = $(this).parent();
					if (myParentz.attr( "href" )) {
						$(this).replaceWith('<span class="sys_ie6PngImgFix ' + this.className + '" style="cursor:pointer;' + filterStart + $(this).attr('src') + "');" + 'width:' + $(this).width() + 'px; height:' + $(this).height() + 'px;'+returnFloat(this)+'"></span>');						
					} else {
						$(this).replaceWith('<span class="sys_ie6PngImgFix ' + this.className + '" style="' + filterStart + $(this).attr('src') + "');" + 'width:' + $(this).width() + 'px; height:' + $(this).height() + 'px;'+returnFloat(this)+'"></span>');
					}
			}
				
		} else {
			this.onload = ie6PngImgFixAction;
		}
	});
}

function returnFloat(objElement) {
	if($(objElement).attr("style").toUpperCase().indexOf("FLOAT: LEFT")>-1 || $(objElement).attr("style").toUpperCase().indexOf("FLOAT:LEFT")>-1)
		return "FLOAT:left;";
	if($(objElement).attr("style").toUpperCase().indexOf("FLOAT: RIGHT")>-1 || $(objElement).attr("style").toUpperCase().indexOf("FLOAT:RIGHT")>-1)
		return "FLOAT:right;";
}

/* Runs if image not is loaded */
function ie6PngImgFixAction() {
	var filterStart = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale src='";
	var filterEnd = "');"
	if($(this).height() > 0) {
		$(this).replaceWith('<span class="sys_ie6PngImgFix ' + this.className + '" style="' + filterStart + $(this).attr('src') + "');" + 'width:' + $(this).width() + 'px; height:' + $(this).height() + 'px;'+returnFloat(this)+'"></span>');
	}
}


/* ------------------------ semi-fixed scrollable positioning ------------------------ */
/** @id posSemiFixed 
*/
function posSemiFixed(me) {
	if (me.offsetWidth > $(window).width()) {
		var left = getScrollXY()[0];
	} else {
		//alert($(window).width() + ' ' + me.offsetWidth);
		var left = ($(window).width() / 2 ) - (me.offsetWidth / 2) + getScrollXY()[0];
	}
	
	if (me.offsetHeight > $(window).height()) {
		var top = getScrollXY()[1];
	} else {
		//alert($(window).height() + ' ' + me.offsetHeight + ' ' + getScrollXY()[1]);
		var top = ($(window).height() / 2 ) - (me.offsetHeight / 2) + getScrollXY()[1];
	}
	
	//alert(left + ' / ' + top);
	
	me.style.left = left + 'px';
	me.style.top = top + 'px';
}

/* ------------------------ Get scrolled distance ------------------------ */
/** @id getScrollXY 
*/
function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) { //Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) { //DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { //IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

/* ======================== Form validation and control ======================== */



/* ------------------------ Replace inputs/buttons with links ------------------------ */
/** @id replace_btns  
*/
function replace_btns(selector) {
	$(selector).each(function(){
		$(this).after('<a href="#" class="genBtn '+this.className+'"><span>' + $(this).val() + '</span></a>');
		if(($.browser.msie) && (parseInt($.browser.version) < 8)) {
			$(this).css('width','0');
		} else if (($.browser.msie) && (parseInt($.browser.version) > 7)) {
			$(this).css('width','0');
			$(this).css('height','0');
			$(this).css('border','0');
		} else {
			$(this).hide();
		}
	});
}

/* ------------------------ Selectbox Auto Post ------------------------ */
/** @id selectboxAutoPost 
*/
function init_selectboxAutoPost() {
	var userAgent = navigator.userAgent;
	var uACheck = userAgent.match('AppleWebKit');
	
	$('.replace_select').hide(); // hide the submit buttons
	
	$('.form_selectAutoPost').each(function(){ // assign events on select boxes
		var selectBox = this;
		if (uACheck != null) {
			selectBox.onchange = selectChangedSafari;
		} else {
			selectBox.changed = false;
			selectBox.onfocus = selectFocused;
			selectBox.onchange = selectChanged;
			selectBox.onkeydown = selectKeyed;
			selectBox.onclick = selectClicked;
		}
	});
	return true;
}


function selectChangedSafari() {
	$(this).trigger('selectAction'); // trigger action of selectbox
}


function selectChanged(theElement) {
	var theSelect;
	if (theElement && theElement.value) {
		theSelect = theElement;
	} else {
		theSelect = this;
	}
	if (!theSelect.changed) {
		return false;
	}
	$(this).trigger('selectAction'); // trigger action of selectbox
	return true;
}


function selectClicked() {
	this.changed = true;
}


function selectFocused() {
	this.initValue = this.value;
	return true;
}

function formSubmitEnter(SubmitButton,e) {
	var theEvent;
	if (e) {
		theEvent = e;
	} else {
		theEvent = event;
	}
	
	if (theEvent.keyCode == "13") {
		$('.'+SubmitButton).click()
	}
}


function selectKeyed(e) {
	var theEvent;
	var keyCodeTab = "9";
	var keyCodeEnter = "13";
	var keyCodeEsc = "27";
	
	if (e) {
		theEvent = e;
	} else {
		theEvent = event;
	}
	
	if (theEvent.keyCode == keyCodeEnter) {
		this.changed = true;
		selectChanged(this);
	} else if (theEvent.keyCode == keyCodeEsc) {
		this.value = this.initValue;
	}
	return true;
}


/* ======================== Debugging ======================== */
/** @id debug 
*/
function debug() {
	if( arguments.length > 0 ) {
		var strs = [];
		
		for( var i=0; i < arguments.length; i++ )
			strs.push(arguments[i]);
		
		var area = document.getElementById("debug");
		
		if( !area ) {
			area = document.createElement("div")
			area.id = "debug";
			area.style["zIndex"] = "10000";
			
			document.body.appendChild(area);
		}
		
		var txt = document.createElement("div");
			txt.innerHTML = strs.join(" :: ");
			txt.className = "entry";
			
		area.appendChild(txt);
		area.scrollTop = area.scrollHeight;
	}
}

/* ======================== fontSizeDependendent ======================== */
/** @id fontSizeDependendent 
*/
function fontSizeDependendent(){
	$('#nav_level1 li a').respectHeight();

	$('.content_standard').each(function(i){
		$('.content_standard:eq('+i+') .rcbContent').respectHeight();
		$('.content_standard:eq('+i+') .rcbHeader').respectHeight();
	});
	
	$('.content_fullTotal_four').each(function(i){
		$('.content_fullTotal_four:eq('+i+') .rcbContent').respectHeight();
		$('.content_fullTotal_four:eq('+i+') .rcbHeader').respectHeight();
	});
	
	$('.module_tab4col').each(function(i){
		$('.module_tab4col:eq('+i+') .tabContentItem').respectHeight();
	});
	
	$('.content_fullTotal_twoSplit').each(function(i){
		$('.content_fullTotal_twoSplit:eq('+i+') .rcbContent').respectHeight();
		$('.content_fullTotal_twoSplit:eq('+i+') .rcbHeader').respectHeight();
	});
	
}

function runPseudoTableMenu() {
	if (($.browser.msie) && (parseInt($.browser.version) < 8)) {
		pseudoTableMenu($('#nav_level1 .sI1 a'),'ul');
		if (telenor.ie6) {
			ie6forceRendering('#nav_level1 .sI1');
		}
	}
}

function runsIFR(strTagType)
{
	if(typeof sIFR == "function"){	
	    sIFR.replaceElement(strTagType, named({sFlashSrc: "/flash/sifr_telenor.swf", sColor: "#0099ff", sWmode: 'opaque'}));
	}
}

/* ======================== Page DOM Loaded ======================== */
/** @id pageDomLoaded  
*/
$(document).ready(function(){
	
	$('.body_sI1').addClass('sys_jsActive'); // for Javascript-dependent CSS 

	/* ------------------------ Bind events ------------------------ */
	$(window).bind('fontResize', function(){
		fontSizeDependendent();
	});
	
	$('input[type=text], input[type=password], textarea').not('.no_highlight')
		.focus(function(){
			$(this).addClass('form_selected');
		})
		.blur(function(){
			$(this).removeClass('form_selected');
		});
	
	
	/* ------------------------ zebra styling ------------------------ */
	$('#footer table tr:even').addClass('style_zebra');
	
	
	/* ------------------------ sIFR ------------------------ */
	runsIFR("h1");
	
	/* ------------------------ replace form elements ------------------------ */
	
	replace_btns('.enhance_btn');
	
	init_selectboxAutoPost();
	
	/* ------------------------ misc ------------------------ */
	fontSizeDependendent();

	if (telenor.ie6) {
		$('#tmpl_home_consumer .contentSection .rcb').each(function(){
			ie6forceRendering(this);
		});
	}
	
	if (telenor.ie6) {
		ie6PngImgFix(); // convert PNG images to IE filter-fixed spans
	}
	
	if (($.browser.mozilla ) && (parseInt($.browser.version) < 3)) {
		$('.body_sI1').addClass('sys_FF3plus'); /* for Firefox 3+ fixes */ 
	}
	
	$('.form_autocompleteOff').attr('autocomplete','off');
	
	if (($.browser.msie) && (parseInt($.browser.version) < 8)) {
		ie_iFrameBuilder();
	}
	
	
	/* ------------------------ ie6FixBottomCorners ------------------------ */
	
	if (telenor.ie6) {
		ie6FixBottomCorners();
	}
	
});



/* ======================== Page Content Loaded ======================== */
/** @id pageContentLoaded  
*/
$(window).load(function(){
	fontSizeDependendent();
});