/**
 * @author oldoffice
 */

//*-FOR DEBUG * JQUERY_COOKIE---------------------------------------------------*//

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        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;
    }
};

//*-/FOR DEBUG * JQUERY_COOKIE---------------------------------------------------*//

//*-FOR DEBUG * JQUERY_PNG---------------------------------------------------*//

/**
 * jQuery (PNG Fix) v1.2
 * Microsoft Internet Explorer 24bit PNG Fix
 *
 * The MIT License
 * 
 * Copyright (c) 2007 Paul Campbell (pauljamescampbell.co.uk)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @param		Object
 * @return		Array
 */
(function($) {
	
	$.fn.pngfix = function(options) {
		
		// Review the Microsoft IE developer library for AlphaImageLoader reference 
		// http://msdn2.microsoft.com/en-us/library/ms532969(VS.85).aspx
		
		// ECMA scope fix
		var elements 	= this;
		var settings 	= $.extend({
			imageFixSrc: 	false,
			sizingMethod: 	false 
		}, options);
		
		if(!$.browser.msie || ($.browser.msie &&  $.browser.version >= 7)) {
			return(elements);
		}

		function setFilter(el, path, mode) {
			var fs = el.attr("filters");
			var alpha = "DXImageTransform.Microsoft.AlphaImageLoader";
			if (fs[alpha]) {
				fs[alpha].enabled = true;
				fs[alpha].src = path; 
				fs[alpha].sizingMethod = mode;
			} else {
				el.css("filter", 'progid:' + alpha + '(enabled="true", sizingMethod="' + mode + '", src="' + path + '")');			
			}
		}
		
		function setDOMElementWidth(el) {
			if(el.css("width") == "auto" & el.css("height") == "auto") {
				el.css("width", el.attr("offsetWidth") + "px");
			}
		}

		return(
			elements.each(function() {
				
				// Scope
				var el = $(this);
				
				if(el.attr("tagName").toUpperCase() == "IMG" && (/\.png/i).test(el.attr("src"))) {
					if(!settings.imageFixSrc) {
						
						// Wrap the <img> in a <span> then apply style/filters, 
						// removing the <img> tag from the final render 
						el.wrap("<span></span>");
						var par = el.parent();
						par.css({
							height: 	el.height(),
							width: 		el.width(),
							display: 	"inline-block"
						});
						setFilter(par, el.attr("src"), "scale");
						el.remove();
					} else if((/\.gif/i).test(settings.imageFixSrc)) {
						
						// Replace the current image with a transparent GIF
						// and apply the filter to the background of the 
						// <img> tag (not the preferred route)
						setDOMElementWidth(el);
						setFilter(el, el.attr("src"), "image");
						el.attr("src", settings.imageFixSrc);
					}
					
				} else {
					var bg = new String(el.css("backgroundImage"));
					var matches = bg.match(/^url\("(.*)"\)$/);
					if(matches && matches.length) {
						
						// Elements with a PNG as a backgroundImage have the
						// filter applied with a sizing method relevant to the 
						// background repeat type
						setDOMElementWidth(el);
						el.css("backgroundImage", "none");
						
						// Restrict scaling methods to valid MSDN defintions (or one custom)
						var sc = "crop";
						if(settings.sizingMethod) {
							sc = settings.sizingMethod;
						} 
						setFilter(el, matches[1], sc);
						
						// Fix IE peek-a-boo bug for internal links
						// within that DOM element
						el.find("a").each(function() {
							$(this).css("position", "relative");
						});
					}
				}
				
			})
		);
	}

})(jQuery)

//*-/FOR DEBUG * JQUERY_PNG---------------------------------------------------*//

//*-FOR FLASH VALUE---------------------------------------------------*//

var valueGetter = function()
{
	this.init.apply(this, arguments);
}

function whichURLPettern()
{
	var curUrl = location.href;
	var checker = curUrl.replace("http://", "");
	//console.log(checker);
	
	if(checker.charAt(0) == "w")
	{
		return "http://www.hanabusaclinic.com/";
	}
	else
	{
		return "http://hanabusaclinic.com/";	
	}
}

var test = whichURLPettern();

valueGetter.prototype = 
{
	month : 0,
	trimKey : test,
	key : "aaa",
	masterKey : "bbb",
	
	init : function()
	{
		//FOR CATEGORY
		var current = location.href;
		this.key = current.replace(this.trimKey, "");
		this.generate();
		
		//FOR MONTH
		this.month = new Date().getMonth();
	},
	
	generate : function()
	{
		var pos = this.key.indexOf("/");
		
		if(pos != -1)
		{
			this.masterKey = this.key.substring(0, pos);
		}
		else
		{
			this.masterKey = "GLOBAL_INDEX";
		}
	},
	
	getCategoryName : function()
	{
		return this.masterKey;
	},
	
	getCurrentMonth : function()
	{
		return this.month;
	}
}

//*-/FOR FLASH VALUE---------------------------------------------------*//

//*-FOR TITLE BACK---------------------------------------------------*//

var month;

function getMonthFromServer()
{
	var key = whichURLPettern();
	var master = key + "common/php/month_check.php";
	//console.log(master);
	
	$.ajax({
	
		url:master,
		success:function(data, status)
		{
			month = data;
			titleSetUp();
		}
	
	});	
}

function titleSetUp()
{
	var currentDir = new valueGetter().getCategoryName();
	var mainPath = "http://www.hanabusaclinic.com/common/images/";
	var indexPath = "http://www.hanabusaclinic.com/images/";
	var fileName;
	var master;
	
	if(currentDir == "GLOBAL_INDEX")
	{
		fileName = "promo" + month;
		master = "url(" + indexPath + fileName + ".jpg)";
		var promoArea = $("div#promo");
		promoArea.css("background-image", master);
		
		var copy = getSeasonCopy(month);
		$("p#promoText").text(copy);
	}
	else
	{
		fileName = "titleback" + month;
		master = "url(" + mainPath + fileName + ".jpg)";
		var titleArea = $("div#contTitle");
		titleArea.css("background-image", master);
	}
}

function getSeasonCopy($month)
{
	var copy;
	switch($month)
	{
		case "01":
			copy = "1月のタイトルバック写真は「胡蝶蘭」。花言葉は「幸福が飛んでくる」です。";
			break;
			
		case "02":
			copy = "2月のタイトルバック写真は「水仙」。花言葉は「神秘」です。";
			break;
			
		case "03":
			copy = "3月のタイトルバック写真は「チューリップ」。花言葉は「永遠の愛情」です。";
			break;
			
		case "04":
			copy = "4月のタイトルバック写真は「さくら」。花言葉は「心の美、精神美」です。";
			break;
			
		case "05":
			copy = "5月のタイトルバック写真は「カーネーション」。花言葉は「美しい仕種」です。";
			break;
			
		case "06":
			copy = "6月のタイトルバック写真は「紫陽花」。花言葉は「辛抱強い愛」です。";
			break;
			
		case "07":
			copy = "7月のタイトルバック写真は「睡蓮」。花言葉は「清浄」です。";
			break;
			
		case "08":
			copy = "8月のタイトルバック写真は「向日葵」。花言葉は「あこがれ、光輝」です。";
			break;
			
		case "09":
			copy = "9月のタイトルバック写真は「ガーベラ」。花言葉は「崇高美」です。";
			break;
			
		case "10":
			copy = "10月のタイトルバック写真は「薔薇」。花言葉は「温かい心」です。";
			break;
			
		case "11":
			copy = "11月のタイトルバック写真は「百合」。花言葉は「高潔」です。";
			break;
			
		case "12":
			copy = "12月のタイトルバック写真は「ポインセチア」。花言葉は「祝福」です。";
			break;
	}	
	
	return copy;
}

function initialLoad()
{
	var preLoadImages = [];
	var imagePath = "http://www.hanabusaclinic.com/common/images/";
	var indexPath = "http://www.hanabusaclinic.com/images/";
	var type = ".jpg";
	var fileName;
	
	if(new valueGetter().getCategoryName() != "GLOBAL_INDEX")
	{
		for(var i = 1; i<=12; i++)
		{
			var fileName;
			i < 10 ? fileName = "titleback0" + i : fileName = "titleback" + i;
			var master = imagePath + fileName + type;
			preLoadImages[i] = new Image();
			preLoadImages[i].src = master;
		}
	}
	else
	{
		for(var i = 1; i<=12; i++)
		{
			var fileName;
			i < 10 ? fileName = "promo0" + i : fileName = "promo" + i;
			var master = indexPath + fileName + type;
			preLoadImages[i] = new Image();
			preLoadImages[i].src = master;
		}
	}
}

//*-FOR TITLE BACK---------------------------------------------------*//


//*-FOR LOCAL_NAVIGATION-----------------------------------------------*//

var infoArr = [];
var current;

function checkEnableToggles()
{
	var enableList = $("ul#mainLn > li > a[href=#]");
	var checker = checkCookie();
	current = new valueGetter().getCategoryName();
	
	infoArr.push(current);
	
	if(checker == null)
	{
		//alert("cookieがありません");
		enableList.each(function()
		{
			this.flag = true;
			setCurrentStyle(this);
		});
	}
	else
	{
		var counter = 1;
		if(checker[0] == current)
		{
			//alert("cookieがあり、同一階層内です。");
			enableList.each(function()
			{
				this.flag = eval(checker[counter]);
				setCurrentStyle(this);
				correctSkin(this)
				counter++;
			});
		}
		else
		{
			//alert("cookieがありますが、他の階層へ移動しました。");
			enableList.each(function()
			{
				this.flag = true;
				setCurrentStyle(this);
				correctSkin(this)
			});
		}
	}
	
	enableList.each(function()
	{
		infoArr.push(this);
		$(this).bind("click", lnToggleFx);
	});
	
	var writer = getWriteArray();
	var ckPath = getCurrentCookiePath();
	$.cookie('state', writer, { path: ckPath });
}

function getCurrentCookiePath()
{
	var ckPath = "/" + current + "/";
	return ckPath;
}

function getWriteArray()
{
	var writer = [];
	for( var i = 0; i < infoArr.length; i++ )
	{
		if( i == 0 )
		{
			writer.push(infoArr[i]);
		}
		else
		{
			writer.push(infoArr[i].flag);
		}
	}
	
	return writer;
}

function checkCookie()
{
	var ck = $.cookie('state');
	
	if(ck != null)
	{
		return cookieToObject(ck);
	}
	else
	{
		return null;
	}
}

function cookieToObject($src)
{
	var info = $src.split(","); 
	return info;
}

function setCurrentStyle($target)
{
	var target = $($target).next();
	if($target.flag == false)
	{
		target.hide();
	} 
}

function lnToggleFx()
{	
	//accordion controll
	var target = $(this).next();	
	target.slideToggle();
	this.flag = !this.flag;
	
	//save state
	var writer = getWriteArray();
	var ckPath = getCurrentCookiePath();
	$.cookie('state', writer, { path: ckPath });
	
	correctSkin(this)
	
	return false;
}

function correctSkin($t)
{
	//change skin
	var skinSrc = $($t).children('img').attr('src');
	var skinType = skinSrc.substring(skinSrc.lastIndexOf('.'), skinSrc.length);
	var fileName = skinSrc.substring(0, skinSrc.length - 4);
	var checkKey = fileName.substring(fileName.length - 3);
	
	if(!$t.flag)
	{
		var file = fileName + "_f2" + skinType;
		$($t).children('img').attr('src', file);
	} 
	else
	{
		var file = fileName.replace("_f2", "") + skinType;
		$($t).children('img').attr('src', file);
	}
}

//*-/FOR LOCAL_NAVIGATION-----------------------------------------------*//

$(document).ready(function(){
	
	initialLoad();
	
	$("div#contTitle img[@src$=png]").pngfix();
	
	//back to top FX
	$("p.bk2Top a").click(function(){
		$.scrollTo(0, 800);
		return false;
	});
	
	checkEnableToggles();
	getMonthFromServer();
	
});
