if(!fh) var fh = {};

fh.rOffset = function(e, standard) {
	// get the offset of standard
	var coord = $(standard).offset();
	
	// measure offset of mouse pointer
	coord.left = e.pageX - coord.left;
	coord.top = e.pageY - coord.top;
	
	return coord;
}

jQuery.fn.relativeOffset = function(standard) {
	var coord = $(this).offset();
	
	coord.left -= $(standard).offset().left;
	coord.top -= $(standard).offset().top;
	
	return coord;
}
jQuery.fn.mouseIsOverThis = function(e) {
	var lefttop = $(this).offset();
	var rightbottom = {right: lefttop.left + $(this).outerWidth(), bottom: lefttop.top + $(this).outerHeight()};
	
	return lefttop.left <= e.pageX && e.pageX <= rightbottom.right && lefttop.top <= e.pageY && e.pageY <= rightbottom.bottom;
}

jQuery.fn.ajaxSubmit = function(type, dataType, handler) {
	$.ajax({
		type: type,
		cache: false,
		url: $(this).attr('action'),
		data: $(this).serialize(),
		dataType: dataType,
		success: handler,
		error: function() { fh.saveError('jQuery.fn.ajaxSubmit -> Ajax Submit Failed!'); alert('새로 고침 후에 다시 시도해 주십시오.'); }
	});
}

fh.rgbToHex = function (rgb) {
    if (rgb.match(/^#[0-9A-Fa-f]{6}$/)) {
        return rgb;
    }
    var rgbvals = /rgb\((.+),(.+),(.+)\)/i.exec(rgb);
    if (!rgbvals) {
        return rgb;
    }
    var rval = parseInt(rgbvals[1]);
    var gval = parseInt(rgbvals[2]);
    var bval = parseInt(rgbvals[3]);
    var pad = function(value) {
        return (value.length < 2 ? '0' : '') + value;
    };
    return '#' + pad(rval.toString(16)) + pad(gval.toString(16)) + pad(bval.toString(16));
}

fh.fitImageIntoParent = function(imageObject) {	
	// get image size information
	var width = imageObject.width();
	var height = imageObject.height();	
	
	// get parent div information
	var parWidth = imageObject.parent().width();
	var parHeight = imageObject.parent().height();	
	
	// if image is smaller than parent
	if(width <= parWidth && height <= parHeight) {
		var top = ( parHeight - height ) / 2;
		
		// set width and height
		imageObject.css({top: top});
		
		return;
	}
	
	// get zoom ratio
	var widthRatio = parWidth / width;
	var heightRatio = parHeight / height;
	var ratio = widthRatio > heightRatio ? heightRatio : widthRatio;
	
	// calculate width and height
	width = parseInt(width * ratio);
	height = parseInt(height * ratio);
	
	var top = ( parHeight - height ) / 2;
	
	// set width and height
	imageObject.css({width: width, height: height, top: top});
}
// resize all magazine lists
fh.relocationImage = function(image) {	

	var widthRatio = image.parent().width() / image.width();
	var heightRatio = image.parent().height() / image.height();
	
	if(widthRatio >= heightRatio) {
		var width = image.parent().width();
		var height = Math.ceil(image.height() * widthRatio);
		var marginTop = Math.ceil((image.parent().height() - height) / 2);
		image.css({width: width, height: height, marginTop: marginTop});
	}
	else {
		var width = Math.ceil(image.width() * heightRatio);
		var height = image.parent().height();
		var marginLeft = Math.ceil((image.parent().width() - width) / 2);
		
		image.css({width: width, height: height, marginLeft: marginLeft});
	}
}
fh.setCommaNumber = function(number) {
	var nStr = number.toString();
	
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

fh.setUrl = function(url) {
	if(url) {
		if(url.startsWith('http://')) return url;
		else if(url.startsWith('https://')) return url;
		else return 'http://'+url;
	}
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function isInt(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) return false; 
	return x==y && x.toString()==y.toString(); 
}

function isUrl(str) {
	var pattern = /^((https?|ftp|gopher|telnet|file|notes|ms-help):((\/\/)|(\\\\))[\w\d:#%\/;$()~_?\-=\\\.&|]*)$/;
	if(!pattern.test(str)) {
		return false;
	} 
	else {
		return true;
	}
}

String.prototype.safeString = function() {
	var result = this;
	result = result.replace(/&/g, '&amp;');
	result = result.replace(/"/g, '&quot;');
	result = result.replace(/'/g, '&#039;');
	result = result.replace(/</g, '&lt;');
	result = result.replace(/>/g, '&gt;');
	result = result.replace(/ /g, '&nbsp;');
	return result;
}

String.prototype.startsWith = function(str){
	return this.substring(0, str.length) === str;
};
String.prototype.endsWith = function(str){
	return this.substring(this.length - str.length) === str;
};

// fix for global container height fix
$('#globalContainer').ready(function() {
	$('#globalContainer').css('min-height', $(window).height());
});
$(window).resize(function() {
	$('#globalContainer').css('min-height', $(window).height());
});

// popup function
fh.popup = function(href, opt) {
	var option = '';
	$.each(opt, function(key, value) {
		if(value) {
			if(option) option += ','
			option += key+'='+value;
		}
	});
	window.open(href,"SwingbeePopup",option);
}

fh.errorText = '\n';

// Save Error for developer to debug 
fh.saveError = function(errorText){
	fh.errorText += errorText + '\n';	
}

// Dynamically load css file
fh.loadCssFile = function(urlList){
	for(var cnt = 0; cnt < urlList.length ; cnt++){		
		$('head').append('<link>');
		css = $('head').children(':last');
		css.attr({
			rel:'stylesheet',
			type:'text/css',
			href:urlList[cnt]
		});
	}
}

$(function() {
	if($.browser.msie && parseInt($.browser.version) == 6) {
		var suggest_update = $("<div id='suggestUpdate'></div>").css('opacity', 0.8);
		suggest_update.append('<h1 style="margin:30px 0px";>현재 브라우저인 Microsoft Explorer 6.0은 스윙비에서 지원하지 않습니다.</br>최신 버전으로 업데이트 하실 것을 권장합니다.</h1>');
		suggest_update.append("<a target='_blank' style='color:white;margin-top:30px;font-size:20px;text-decoration:underline;' href='http://windows.microsoft.com/ko-KR/internet-explorer/downloads/ie'>최신 버전 Microsoft Explorer 다운로드</a>");
		
		suggest_update.appendTo('body');
	}
});