var _text = new Array;
_text["%d day(s)"] = "%d 일";
_text["%d day(s) %d hour(s)"] = "%d 일 %d 시간";
_text["%d hour(s)"] = "%d 시간";
_text["%d hour(s) %d minute(s)"] = "%d 시간 %d 분";
_text["%d minute(s)"] = "%d 분";
_text["%d sec(s)"] = "%d 초";
_text["%s added the his <a href=\"%s\">story</a>"] = "%s님이 <a href=\"%s\">스토리</a>를 등록 하셨습니다 ";
_text["%s after"] = "%s 후";
_text["%s before"] = "%s 전";
_text["%s group created"] = "'%s' 그룹이 생성되었습니다";
_text["%s group removed"] = "'%s' 그룹이 삭제되었습니다";
_text["%s posted the <a href=\"%s\">photo talk</a>"] = "%s 님이<a href=\"%s\">포토Talk</a>를 남기셨습니다 ";
_text["%s posted the <a href=\"%s\">story talk</a>"] = "%s님이 <a href=\"%s\">스토리 Talk</a>를 남기셨습니다 ";
_text["%s removed from your network"] = "'%s' 과 친구관계를 끊었습니다";
_text["%s supports OpenID."] = "%s은 OpenID를 지원합니다";
_text["%s updated his <a href=\"%s\">photo album</a>"] = "%s님의 <a href=\"%s\">포토앨범</a>에 사진이 등록되었습니다 ";
_text["(Ex: 1984-01-31)"] = "(예: 1984-01-31)";
_text["(Ex: Movie, Sports, Cars)"] = "(예: 영화,스포츠,자동차)";
_text["<a href=\"%1\">%2</a> replied to your comment in %4's <a href=\"%3\">photo talk</a>"] = "%4님의 포토앨범에 남긴 <a href=\"%3\">포토Talk</a>에 <a href=\"%1\">%2</a>님이 답변하였습니다";
_text["<a href=\"%1\">%2</a> replied to your comment in %4's <a href=\"%3\">story talk</a>"] = "%4님의 스토리에 남긴 <a href=\"%3\">댓글</a>에 <a href=\"%1\">%2</a>님이 답변하였습니다";
_text["<a href=\"%1\">%2</a> replied to your comment in <a href=\"%3\">%4</a>'s guest book"] = "%4님의 <a href=\"%3\">방명록</a>에 남긴글에 <a href=\"%1\">%2</a>님이 답변하였습니다.";
_text["<a href=\"%s\">%s</a> accept your invitaion"] = "<a href=\"%s\">%s</a>님이 지인초대를 수락하였습니다.";
_text["<a href=\"%s\">%s</a> accept your network request"] = "<a href=\"%s\">%s</a>님이 친구신청을 수락하였습니다.";
_text["<a href=\"%s\">%s</a> added the %s mytem"] = "<a href=\"%s\">%s</a>님이 %s 마이템을 추가하였습니다.";
_text["<a href=\"%s\">%s</a> and <a href=\"%s\">%s</a> became a friend "] = "<a href=\"%s\">%s</a>님과 <a href=\"%s\">%s</a>님이 친구가 되었습니다 ";
_text["<a href=\"%s\">%s</a> changed her picture"] = "<a href=\"%s\">%s</a>님이 사진을 업데이트 하였습니다.";
_text["<a href=\"%s\">%s</a> changed his picture"] = "<a href=\"%s\">%s</a>님이 사진을 업데이트 하였습니다.";
_text["<a href=\"%s\">%s</a> changed his primary email"] = "<a href=\"%s\">%s</a>님이 메일을 업데이트 하였습니다.";
_text["<a href=\"%s\">%s</a> made friend with <a href=\"%s\">%s</a>"] = "<a href=\"%s\">%s</a>님이 <a href=\"%s\">%s</a>님과 친구가 되었습니다.";
_text["<a href=\"%s\">%s</a> replied to on your <a href=\"%s\">guest book</a>"] = "<a href=\"%s\">%s</a>님이 <a href=\"%s\">방명록</a>에 답변을 남겼습니다.";
_text["<a href=\"%s\">%s</a> updated her career inforamtion"] = "<a href=\"%s\">%s</a>님의 회사정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated her interest fields"] = "<a href=\"%s\">%s</a>님의 관심분야가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated her local inforamtion"] = "<a href=\"%s\">%s</a>님의 지역정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated her messenger information"] = "<a href=\"%s\">%s</a>님의 메신저 정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated her school inforamtion"] = "<a href=\"%s\">%s</a>님의 학교정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated her website information"] = "<a href=\"%s\">%s</a>님의 웹사이트 정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated his career inforamtion"] = "<a href=\"%s\">%s</a>님의 회사정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated his interest fields"] = "<a href=\"%s\">%s</a>님의 관심분야가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated his local inforamtion"] = "<a href=\"%s\">%s</a>님의 지역정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated his messenger information"] = "<a href=\"%s\">%s</a>님의 메신저 정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated his school inforamtion"] = "<a href=\"%s\">%s</a>님의 학교정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> updated his website information"] = "<a href=\"%s\">%s</a>님의 웹사이트 정보가 업데이트 되었습니다.";
_text["<a href=\"%s\">%s</a> wrote a comment on your <a href=\"%s\">guest book</a>"] = "<a href=\"%s\">%s</a>님이 <a href=\"%s\">방명록</a>에 글을 남겼습니다.";
_text["<a href=\"/users/openid_enable\" class=\"btn_l red\">Enable OpenID</a> <span class=\"text\">as</span> <span class=\"openid2\">%s</span>"] = "<span class=\"openid2\">%s</span> <span class=\"text\">을</span> <a href=\"/users/openid_enable\" class=\"btn_l red\">오픈아이디로 사용하기</a>";
_text["<b>%s</b> will be issued as your ID"] = "<b>%s</b>으로 발급됩니다.";
_text["<span>%s</span> supports OpenID"] = "<span>%s</span>은 OpenID를 지원합니다";
_text["<span>*</span> marks are required fields"] = "'<span>*</span>' 표시는 필수 입력 항목입니다";
_text["<span>Notice</span> Some mail providers classify this mail as a spam, check your spam mail box if not deliverred"] = "<span>알림</span> 일부 메일의 경우 스팸함으로 메일이 전송되는 경우가 있으니 꼭 확인해주십시오.";
_text["<span>Set your own <b>antiphishing image</b> on this machine</span>"] = "<span><b>피싱방지 이미지</b>를<br />설정하세요</span>";
_text["ACL Edit"] = "정보공개 설정";
_text["AOL"] = "AOL";
_text["Accept"] = "수락";
_text["Access control by group"] = "그룹별 정보공개 설정";
_text["Access privilege about your information can be set at the left top quick menu"] = "입력하신 정보에 대한 공개 범위는 왼쪽의 바로가기 메뉴의 환경설정에서 변경하실 수 있습니다";
_text["Access rights"] = "정보공개 설정";
_text["Add"] = "추가";
_text["Add IDtail login bookmarklet to your browser bookmark and just click it on login!"] = "IDtail 로그인 북마클릿을 브라우져의 즐겨찾기에 추가하시고 오픈아이디 로그인이 필요한 사이트에서 추가한 북마클릿만 클릭해 보세요! 오픈아이디를 입력하지 않아도 클릭만으로 로그인하실 수 있습니다.";
_text["Add another OpenID"] = "다른 오픈아이디 추가";
_text["Add more career"] = "다른 회사 추가";
_text["Add school"] = "학교 추가";
_text["Added"] = "추가됨";
_text["Adding to my mytem"] = "마이템에 추가하기";
_text["Additional date"] = "추가일";
_text["Address loading is failed"] = "주소를 가져오지 못했습니다";
_text["Admin : Seceder List"] = "탈퇴자 목록";
_text["Admin : User List"] = "회원 목록";
_text["Admin : User Profile"] = "회원 정보";
_text["Administration"] = "관리";
_text["Affiliation program"] = "공동 가입";
_text["Age"] = "나이";
_text["Ajax deletion not supported"] = "Ajax 삭제가 지원되지 않습니다";
_text["Ajax object creation not supported"] = "Ajax 개체 생성이 지원되지 않습니다";
_text["Ajax update is not implemented"] = "Ajax 수정이 구현되지 않았습니다";
_text["Ajax update is not supported"] = "Ajax 수정이 지원되지 않습니다";
_text["All"] = "전체";
_text["All friends"] = "모든 친구";
_text["Already Networked"] = "이미 친구임";
_text["Already confirmed email"] = "이미 확인된 이메일입니다";
_text["Already occupied username"] = "이미 사용중인 아이디입니다";
_text["Already registerred email"] = "이미 등록된 이메일입니다";
_text["Already registerred openid"] = "이미 등록된 오픈아이디입니다";
_text["Already registerred to another ID,  Owner : "] = "이미 등록된 오픈아이디입니다. 소유자 : ";
_text["And more information is required"] = "위 사이트에서 아래의 정보 제공을 요청합니다";
_text["Antenna"] = "안테나";
_text["Anti-phishing"] = "피싱방지";
_text["Anti-phishing image"] = "피싱방지 이미지";
_text["Antiphishing image"] = "피싱방지 이미지";
_text["Antiphishing image is deleted"] = "피싱방지 이미지가 삭제되었습니다";
_text["Antiphishing sentence is cleared"] = "피싱방지 문구가 삭제되었습니다";
_text["Antiphishing sentence is not changed"] = "피싱방지 문구가 변경되지 않았습니다";
_text["Antiphishing sentence is updated"] = "피싱방지 문구가 변경되었습니다";
_text["Antiphishing setting is updated"] = "피싱방지 설정이 변경되었습니다";
_text["Application"] = "어플리케이션";
_text["Application id is empty"] = "어플리케이션 아이디가 없습니다.";
_text["Application will have a it`s own permerlink by english name"] = "영문명으로 어플리케이션의 고정URL이 생성됩니다";
_text["Are you sure to remove your friend?"] = "정말 친구관계를 끊으시겠습니까?";
_text["Asia"] = "아시아";
_text["Ask for Information"] = "문의하기";
_text["Austrailia"] = "오스트렐리아";
_text["Authentication failed"] = "인증에 실패하였습니다";
_text["Available email"] = "사용가능한 주소입니다";
_text["Available length is 6~20"] = "6자 이상 20자 이하로 입력하세요";
_text["Available openid"] = "사용가능한 오픈아이디입니다";
_text["Bachelor"] = "학사";
_text["Bad Request"] = "잘못된 요청";
_text["Basic Info"] = "기본 정보";
_text["Basic info"] = "기본 정보";
_text["Basic profile information"] = "기본 프로필 정보";
_text["Begin year"] = "연도선택";
_text["Birth year"] = "생년";
_text["Blog"] = "블로그";
_text["Blogs"] = "블로그";
_text["Both passwords are different"] = "두 비밀번호가 서로 다릅니다";
_text["Both passwords are mismatched."] = "두 비밀번호가 서로 다릅니다";
_text["Brief"] = "한 줄 소개";
_text["Buddy list that you selected is empty"] = "선택하신 주소록에 친구 명단이 없습니다";
_text["Can't save your photo"] = "사진을 저장할 수 없습니다";
_text["Canada"] = "캐나다";
_text["Cancel"] = "취소";
_text["Card view"] = "명함으로 보기";
_text["Career"] = "회사";
_text["Career information saved"] = "회사 정보가 저장되었씁니다";
_text["Careers"] = "회사정보";
_text["Cell phone"] = "이동전화";
_text["Celluar phone"] = "이동전화";
_text["Cellular phone number"] = "이동전화";
_text["Change passwords"] = "비밀번호 변경";
_text["Changed to use OpenID"] = "오픈아이디로 사용하도록 변경되었습니다";
_text["Chat key is cleared"] = "Chat key가 발급되었습니다.";
_text["Cheat key is not changed"] = "치트 키가 변경되지 않았습니다";
_text["Cheat key is set on your browser cookie"] = "치트키가 브라우져 쿠키에 설정되었습니다";
_text["Cheat key is set on your browser, and works even if you are not logged in"] = "치트키가 설정되었습니다. 이것은 로그인하지 않은 상태에서도 유효합니다";
_text["Cheat key to exploit idtail.com"] = "idtail.com을 유용하게 활용할 치트키를 입력하세요";
_text["Check email"] = "이메일을 확인하세요";
_text["Check login session..."] = "로그인 여부를 확인중입니다..";
_text["Check password"] = "비밀번호를 확인하세요";
_text["Check quiz"] = "그림퀴즈를 확인하세요";
_text["Check the duplication"] = "중복 확인";
_text["Check your id"] = "아이디를 확인하세요";
_text["China"] = "중국";
_text["Choose"] = "선택하세요";
_text["Choose an IM"] = "선택하세요";
_text["Choose receivers"] = "수신자 수";
_text["Choose your favorite theme"] = "원하시는 명함을 선택해 주세요";
_text["Choose..."] = "선택하세요";
_text["Choosing in the group"] = "친구목록에서 선택";
_text["Click your right mouse button on this link and select \"Add to favorite\" (Internet Explorer) or \"Add to bookmark (Firefox)\""] = "인터넷 익스플로러를 사용하시는 분은 상단 로그인 북마클릿 이미지에 마우스 오른쪽 버튼을 클릭>즐겨찾기에 추가”하시고, FFirefox를 사용하시는 분은 좌측 이미지를 마우스 드래그를 이용하여 북마크 도구 모음에 추가하실 수 있습니다.";
_text["Close"] = "닫기";
_text["College"] = "대학";
_text["Companies"] = "회사 정보";
_text["Company"] = "회사";
_text["Company name"] = "회사 이름";
_text["Company title"] = "직위";
_text["Confirm"] = "확인";
_text["Confirm mail sent, please check your mail box"] = "확인메일이 발송되었습니다. 메일함을 확인하세요";
_text["Confirm your new password"] = "비밀번호 확인";
_text["Confirmed"] = "확인됨";
_text["Contact"] = "연락처";
_text["Contact us"] = "고객 문의";
_text["Contacts"] = "연락처";
_text["Copied URL to clipboard"] = "URL이 클립보드에 복사되었습니다";
_text["Correct"] = "일치합니다";
_text["Country number"] = "국가 코드";
_text["Create your api key!"] = "Api Key 발급";
_text["Current"] = "재직중";
_text["Current job"] = "재직중";
_text["Current password"] = "현재 비밀번호";
_text["Currently <b>%s</b> is logged in."] = "현재 로그인된 계정은 <b>%s</b>입니다";
_text["Cyworld"] = "싸이월드";
_text["Cyworld Paper"] = "싸이월드 페이퍼";
_text["Date"] = "날짜";
_text["Daum blog"] = "다음 블로그";
_text["Day"] = "일";
_text["Day of birth"] = "생년월일";
_text["Day of birth will not be displayed publicly"] = "생년월일은 타인에게 공개되지 않습니다";
_text["Default Edit"] = "기본설정";
_text["Default groups are cannot be removed"] = "기본 그룹은 삭제할 수 없습니다";
_text["Degree"] = "학위";
_text["Delete"] = "삭제";
_text["Delete action is available only to owner and writer"] = "삭제 권한이 없습니다";
_text["Delete image"] = "등록된 이미지 삭제";
_text["Deleted"] = "삭제됨";
_text["Deleted or not existed transaction"] = "존재하지 않는 트랜잭션입니다.";
_text["Deletion"] = "삭제";
_text["Description"] = "설명";
_text["Disconnect network"] = "친구 끊기";
_text["Division"] = "부서";
_text["Do you really remove all applicatins in tihe tabs"] = "정말 이 어플리케이션을 삭제하시겠습니까?";
_text["Do you really want to remove the selected application(s)?"] = "정말 이 마이템을 삭제하시겠습니까?";
_text["Do you really want to remove the selected applications"] = "정말 선택한 마이템을 삭제하시겠습니까?";
_text["Do you want to change all groups?"] = "그룹명을 전체에 적용하시겠습니까?";
_text["Do you want to check added application?"] = "추가한 마이템을 확인하시겠습니까?";
_text["Doctor"] = "박사";
_text["E-mail"] = "이메일";
_text["EULA"] = "이용약관";
_text["Edit Mytem"] = "마이템 수정";
_text["Edit photo"] = "사진편집하기";
_text["Egloos"] = "이글루스";
_text["Elementary school"] = "초등학교";
_text["Email"] = "이메일";
_text["Email allowance"] = "메일 허용";
_text["Email confirmation"] = "이메일 확인";
_text["Emails"] = "이메일";
_text["Empas blog"] = "엠파스 블로그";
_text["Empty username"] = "사용자명이 비어 있습니다.";
_text["Encrypting password..."] = "비밀번호를 암호화 중입니다.";
_text["End user license agreement"] = "이용약관";
_text["End year"] = "연도선택";
_text["England"] = "영국";
_text["Ent. Year"] = "년도";
_text["Enter Blog URL"] = "블로그 URL을 입력하세요";
_text["Enter ID"] = "ID를 입력하세요";
_text["Enter RSS url"] = "RSS 주소를 입력하세요";
_text["Entrance year"] = "입학년도(학번)";
_text["Error : require 1 param"] = "오류 : 하나 이상의 파라메터가 필요합니다.";
_text["Error not exist gadget content"] = "오류 : 가젯 컨텐츠가 존재하지 않습니다.";
_text["Error occurred in deleting account"] = "계정을 삭제하는데 오류가 발생하였습니다";
_text["Europe"] = "유럽";
_text["Everyone in your buddy list are already idtail users"] = "추가하는 모든 사람이 이미 idtil 회원입니다";
_text["Ex)"] = "예)";
_text["Ex)hedgeplus.idtail.com"] = "예)hedgeplus.idtail.com";
_text["Existed username"] = "존재하는 사용자 입니다";
_text["Explosure on profile"] = "프로필 노출";
_text["FAQ"] = "자주 묻는 질문";
_text["FAX"] = "팩스";
_text["Failed"] = "저장하지 못함";
_text["Failure"] = "실패";
_text["Favorite Location"] = "자주 머무는 곳";
_text["Female"] = "여자";
_text["Fill or set blank field(s)"] = "빈 칸을 채워주세요";
_text["Find"] = "찾기";
_text["Find ID"] = "아이디 찾기";
_text["Find ID/Password"] = "아이디 및 비밀번호 찾기";
_text["Find password"] = "비밀번호 찾기";
_text["Find username/password"] = "아이디 및 비밀번호 찾기";
_text["FlickR"] = "플리커";
_text["Flickr"] = "플리커";
_text["France"] = "프랑스";
_text["Friend request status"] = "친구 신청 현황";
_text["Friend request will be automatically rejected if there is no reaction after request"] = "한달 동안 친구 신청을 수락하지 않으시면 자동으로 친구신청이 거절됩니다";
_text["Friends"] = "친구";
_text["Friends List"] = "친구목록";
_text["Friends group management"] = "친구 그룹 관리";
_text["GTalk"] = "GTalk";
_text["Gender"] = "성별";
_text["Go to edit mydtail"] = "마이디테일 페이지로";
_text["Grad. year"] = "졸업년도";
_text["Graduate"] = "졸업";
_text["Group"] = "그룹";
_text["Guest Book"] = "방명록";
_text["Guestbook"] = "방명록";
_text["He/She also requested to you. So, your request is automatically accepted"] = "이미 친구신청을 받은 상태이므로, 본 신청은 자동 수락됩니다.";
_text["He/She has informed your network request. So, you cannot request network in a month"] = "상대가 친구신청을 거절한 상태이므로 한 달간 신청하실 수 없습니다";
_text["He/She has rejected your network request. So, you cannot request network in a month"] = "상대가 친구신청을 거절한 상태이므로 한 달간 신청하실 수 없습니다";
_text["Hedgeplus"] = "고슴도치플러스";
_text["Help"] = "문의하기";
_text["Hidden"] = "비공개";
_text["High school"] = "고등학교";
_text["Home page"] = "홈 페이지";
_text["How to add this bookmarklet to a browser"] = "북마클릿을 나의 브라우져에 추가하는 법";
_text["I forgot my id"] = "아이디 찾기";
_text["I forgot my password"] = "비밀번호 찾기";
_text["I think this is not a image file"] = "이미지 형식의 파일이 아닙니다";
_text["ICQ"] = "ICQ";
_text["ID"] = "아이디";
_text["ID or Password is wrong"] = "아이디 혹은 비밀번호가 틀립니다";
_text["IDtail Labs Update"] = "IDtail Lab 업데이트";
_text["IDtail api key"] = "IDtail Api Key ";
_text["IDtail login bookmarklet"] = "IDtail 로그인 북마클릿";
_text["IDtail story"] = "아이디테일 이야기";
_text["IDtail supports OpenID provider"] = "아이디테일의 오픈아이디를 사용하시는 분께만 제공되는 기능입니다";
_text["IM"] = "메신저";
_text["Id"] = "아이디";
_text["Idtail Labs"] = "아이디테일 Labs";
_text["Idtail Story"] = "아이디테일 이야기";
_text["If you delete the application, that is never restore. Do you want to remove the application?"] = "어플리케이션을 삭제하시면 복구할 수 없습니다. 정말 삭제하시겠습니까?";
_text["If you don`t delete all applictions in selected tab, You can`t remove this tab"] = "선택된 탭을 삭제하시려면, 어플리케이션을 먼저 삭제해야합니다";
_text["If you publish the application, you can`t remove that. continue?"] = "어플리케이션을 발행하시면 제거할 수 없습니다. 계속하시겠습니까?";
_text["Illegal Access"] = "잘못된 접근입니다";
_text["Image Quiz"] = "그림 퀴즈";
_text["Incorrect"] = "일치하지 않습니다";
_text["Incorrect string picture word"] = "그림파일의 단어와 다릅니다";
_text["Industry"] = "직군";
_text["Inform"] = "확인";
_text["Input 3 or 4 characters"] = "3~4 글자를 입력하세요";
_text["Input OpenID or ID issued by IDtail"] = "오픈아이디 혹은 IDtail 아이디를 넣어 주세요";
_text["Input a OpenID"] = "오픈아이디 입력";
_text["Input company"] = "회사명으로 검색";
_text["Input fullname"] = "이름으로 검색";
_text["Input manually"] = "직접 입력";
_text["Input school"] = "학교명으로 검색";
_text["Input your ID"] = "사용자 아이디를 입력하세요";
_text["Input your real name"] = "가능한한 실명을 입력해 주세요";
_text["Inputdata is null"] = "입력값이 없습니다.";
_text["Interest"] = "관심";
_text["Interestings"] = "관심분야";
_text["Interests"] = "관심분야";
_text["Internal error: Ajax update is not implemented"] = "내부 오류: Ajax 업데이트가 처리되지 않았습니다.";
_text["Internal error: model not loaded"] = "내부 오류: model not loaded";
_text["Internal system error"] = "시스템 내부 오류";
_text["Invalid access"] = "잘못된 접근입니다";
_text["Invalid data"] = "잘못된 날짜 형식입니다";
_text["Invalid format"] = "잘못된 형식입니다";
_text["Invalid password"] = "비밀번호가 맞지 않습니다";
_text["Invitation key is not exist"] = "초대 정보가 존재하지 않습니다";
_text["Invite"] = "지인 초대하기";
_text["Invite Now!"] = "초대하기";
_text["Invite accept"] = "초대 수락";
_text["Invite from address book"] = "주소록으로 초대하기";
_text["Invite via address book"] = "주소록으로 초대하기";
_text["Invite via email"] = "이메일로 직접 초대하기";
_text["It helps you type openid conveniently<br />Click \"[Make with other OpenID]\" to make a bookmarklet associated with another OpenID"] = "<br />  또한 아래의 [다른 OpenID 북마클릿 만들기]를 클릭하시면 IDtail의 OpenID 외에도 다른 OpenID, 또는 위임하여 사용하시는 OpenID의 북마클릿을 만드실 수 있습니다.";
_text["Japan"] = "일본";
_text["Junior Join"] = "14세 미만 가입";
_text["Keep login in a week"] = "일주일간 로그인 유지";
_text["Korea"] = "대한민국";
_text["Korean apache users group"] = "아파치 사용자 그룹";
_text["LOCAL-EMAIL-LIST"] = "naver.com naver.com/hanmail.net hanmail.net/daum.net daum.net/hotmail.com hotmail.com/gmail.com gmail.com/yahoo.co.kr yahoo.co.kr/empal.com empal.com/chollian.net chollian.net/chol.com chol.com/freechal.com freechal.com/hanafos.com hanafos.com/kebi.com kebi.com/korea.com korea.com/lycos.co.kr lycos.co.kr/netian.com netian.com/netsgo.com netsgo.com/paran.com paran.com/unitel.co.kr unitel.co.kr";
_text["Leave your comment about this mytem (up to 1000 chars.)"] = "리뷰를 남겨주세요(1000자이내)";
_text["Leave your message to send(upto 1000 chars.)"] = "전하시고 싶은 글을 남겨주세요(1000자이내)";
_text["List"] = "목록";
_text["List icon"] = "목록 아이콘";
_text["List view"] = "리스트로 보기";
_text["Loading address..."] = "주소록 여는 중...";
_text["Locals"] = "지역정보";
_text["Location"] = "지역";
_text["Location %s / %s is already exists"] = "%s, %s 는 이미 존재하는 지역명입니다";
_text["Location text length can't exceed 20 bytes"] = "위치 문자열은 10자를 넘을 수 없습니다";
_text["Locations"] = "지역";
_text["Logged at %m-%d %H:%M"] = "로그인한 시간: %m-%d %H:%M";
_text["Login"] = "로그인";
_text["Login information is wrong. <br /> Please check your ID and Password again."] = "입력하신 정보가 정확하지 않습니다.<br /> 해당 아이디와 비밀번호를 다시 확인하여 주십시오.";
_text["Login to invite a person"] = "친구를 추천을 하시려면 로그인을 해 주세요";
_text["Logout"] = "로그아웃";
_text["MSN"] = "MSN";
_text["Mail send failure, try later"] = "메일 전송에 실패하였습니다. 나중에 다시 시도하십시오";
_text["Mail sent"] = "메일이 발송 되었습니다";
_text["Major"] = "전공";
_text["Make Mydtail"] = "마이디테일 만들기";
_text["Make up your page and build your valuable network"] = "나를 표현하고 많은 사람들과 유익한 친구 관계를 만들어 보세요";
_text["Make with other OpenID"] = "다른 OpenID 북마클릿 만들기";
_text["Make your own name card in IDtail!"] = "IDtail에서 나만의 명함을 만들어 보세요!";
_text["Makeup your mydtail"] = "마이디테일 페이지 만들기";
_text["Male"] = "남자";
_text["Margarin"] = "마가린";
_text["Master"] = "석사";
_text["Me2day"] = "미투데이";
_text["Message is empty"] = "메시지가 비었습니다";
_text["Messenger"] = "메신저";
_text["Messenger added"] = "메신저가 추가되었습니다";
_text["Messenger delete"] = "메신저가 삭제되었습니다";
_text["Messengers"] = "메신저";
_text["Middle school"] = "중학교";
_text["Model[%s] is not included in uses array (occured from %s : %s)"] = "Model[%s] is not included in uses array (occured from %s : %s)";
_text["Modify"] = "수정";
_text["Month"] = "월";
_text["More about you"] = "상세 정보 입력";
_text["Move to this group"] = "그룹 이동";
_text["My IDtail ID"] = "내 마이디테일 아이디";
_text["My OpenID"] = "나의 오픈아이디";
_text["My invitations"] = "나의 초대현황";
_text["Mydtail Mng."] = "마이디테일 관리";
_text["Mydtail Registration"] = "마이디테일 추가";
_text["Mydtail is an url provided by IDtail, at which <span class=\"openid\">your identity is presented</span>"] = "마이디테일은  IDtail에서 만들 수 있는 <span class=\"openid\">나만의 아이덴티티를 표현하는 url</span>입니다";
_text["Mydtail user added"] = "마이디테일 페이지가 생성되었습니다";
_text["Mydtail user added failure"] = "마이디테일 페이지를 생성하지 못했습니다";
_text["Myself"] = "본인";
_text["Mytem Management"] = "마이템 관리";
_text["Mytem directory"] = "마이템 디렉토리";
_text["Mytem informed to administrator"] = "관리자에게 신고하였습니다";
_text["Mytem management"] = "마이템 관리";
_text["Name"] = "이름";
_text["Name card"] = "나의 ID Card";
_text["Nate tong"] = "네이트 통";
_text["NateOn"] = "네이트온";
_text["Nation"] = "국가";
_text["Naver blog"] = "네이버 블로그";
_text["Network"] = "네트워크";
_text["NetworkRelation's status is not Accept. Cannot remove"] = "현재 친구관계가 수락 상태가 아닙니다. 친구관계를 끊을 수 없습니다";
_text["New Mytem"] = "마이템 신규 등록";
_text["New password"] = "새 비밀번호";
_text["Next"] = "다음";
_text["Nick name"] = "닉네임";
_text["Nickname"] = "닉네임";
_text["No file was uploaded"] = "업로드된 사진이 없습니다";
_text["No openid input form detected"] = "오픈아이디 입력 폼이 없습니다";
_text["No photo"] = "등록된 사진 없음";
_text["No such user"] = "존재하지 않는 사용자입니다";
_text["None"] = "없음";
_text["Nonexistent transaction"] = "존재하지 않는 트랜잭션입니다.";
_text["Not confirmed"] = "확인되지 않음";
_text["Not exist app key"] = "존재하지 않는 어플리케이션 키 입니다";
_text["Not exist user"] = "존재하지 않는 사용자 입니다";
_text["Not existed news"] = "존재하지 않는 뉴스입니다";
_text["Not existed username"] = "존재하지 않는 사용자 입니다";
_text["Not found"] = "페이지를 찾을 수 없습니다";
_text["Not installed application"] = "설치하지 않은 어플리케이션입니다";
_text["Not logged in session"] = "로그인 세션이 아닙니다";
_text["Not registerred email, check your contacts information"] = "추가되지 않은 메일을 확인하려고 합니다. 연락처를 확인하세요";
_text["Not registerred openid user. report this error please"] = "등록되지 않은 OpenID 사용자입니다. (내부 오류입니다)";
_text["Not yet added email"] = "아직 추가되지 않은 이메일입니다";
_text["Notes"] = "쪽지";
_text["Notes box"] = "쪽지함";
_text["Notice"] = "알림";
_text["Notification allowance"] = "안테나 허용";
_text["Notifing to friends"] = "친구에게 알리기";
_text["Notifying to friends"] = "친구에게 알려주기";
_text["Now"] = "현재";
_text["Open to all"] = "전체 공개";
_text["Open to network"] = "친구 공개";
_text["Open to only my friends"] = "친구 공개";
_text["Open to only my network"] = "친구 공개";
_text["OpenID"] = "오픈아이디";
_text["OpenID Management"] = "오픈아이디 관리";
_text["OpenID authentication failed"] = "인증에 실패하였습니다";
_text["Other"] = "그 외";
_text["Other OpenID"] = "다른 오픈아이디";
_text["Other emails"] = "다른 이메일";
_text["Paran blog"] = "파란 블로그";
_text["Partner program"] = "제휴안내";
_text["Password"] = "비밀번호";
_text["Password changed"] = "비밀번호가 바뀌었습니다";
_text["Phone"] = "전화번호";
_text["Phone number"] = "전화번호";
_text["Photo"] = "사진";
_text["Photo album/Mytem/Stories"] = "포토앨범/마이템/스토리";
_text["Photo list"] = "사진 목록";
_text["Playtalk"] = "플레이톡";
_text["Please fill a location field with right text"] = "적합한 지역명을 입력해주세요";
_text["Please fill out the contents"] = "내용을 작성해 주세요";
_text["Please fill out the this textarea"] = "내용을 작성해 주세요";
_text["Please input review within 1000 chars"] = "1000 글자 이내로 작성해 주세요";
_text["Please input the word you want to search"] = "찾고 싶은 단어를 입력하세요";
_text["Please leave a message"] = "내용을 입력해 주세요";
_text["Please login first for secede"] = "탈퇴하시려면 로그인을 해야합니다";
_text["Please wait; you are being redirected to <%s>"] = "잠시만 기다리십시오. <%s>로 이동합니다.";
_text["Please write the your valuation of this application.(within 1000 words)"] = "마이템에 대한 평가를 해주세요(1000자이내)";
_text["Please, fill your full name"] = "이름을 입력해 주세요";
_text["Prev"] = "이전";
_text["Primary email"] = "주로 사용하는 메일";
_text["Privacy"] = "개인정보취급방침";
_text["Privacy Policy"] = "개인정보취급방침";
_text["Privacy policy"] = "개인정보 취급방침";
_text["Private message"] = "비밀글";
_text["Profile Edit"] = "프로필 관리";
_text["Profile access control by Group"] = "그룹별 상세 설정";
_text["Profile image"] = "프로필 사진";
_text["Property <span>%s</span>  setting"] = "<span>%s</span>에 대한 설정입니다";
_text["Pumfit"] = "펌핏";
_text["Read"] = "읽음";
_text["Real name"] = "이름";
_text["Real name will help us to build your network"] = "실명을 입력하시면 보다 폭넓은 친구관계를 맺으실 수 있습니다";
_text["Receive IDtail.com event or news via email"] = "IDtail의 이벤트나 새소식을 이메일로 수신합니다";
_text["Receive User"] = "받는사람";
_text["Received Date"] = "받은 날짜";
_text["Received User"] = "받는 사람";
_text["Received notes"] = "받은 쪽지";
_text["Received req."] = "신청 현황";
_text["Received request"] = "받은 신청";
_text["Receiver"] = "받는사람";
_text["Recent visitors"] = "최근 방문자";
_text["Recommend Network"] = "추천 네트워크";
_text["Record remove failed"] = "레코드 삭제 실패";
_text["Record removed"] = "레코드 삭제됨";
_text["Record updated"] = "레코드 업데이트됨";
_text["Refresh failed"] = "새로고침 실패";
_text["Refreshing RSS..."] = "RSS를 새로 고치는 중...";
_text["Register your articles"] = "나와 관련된 웹사이트 주소들을 마이디테일에 모아보세요.";
_text["Register your web services which support RSS feeds"] = "RSS를 지원하는 웹서비스를 등록하세요";
_text["Reject"] = "거절";
_text["Relying parties"] = "적용 사이트";
_text["Remember ID"] = "아이디 저장";
_text["Removed"] = "친구삭제";
_text["Rename failure"] = "이름변경 실패";
_text["Renew your api key?"] = "Api key 재발급";
_text["Reply"] = "답변";
_text["Request confirm"] = "승인요청";
_text["Request network"] = "친구 신청";
_text["Resend"] = "재전송";
_text["Resize error"] = "크기조절 실패";
_text["Retype password"] = "비밀번호 확인";
_text["Safe login"] = "안전 로그인";
_text["Safe login is set"] = "안전 로그인이 설정되었습니다";
_text["Safe login is unset"] = "안전 로그인이 해제되었습니다";
_text["Safe login?"] = "안전 로그인이란?";
_text["Same passwords are entered"] = "두 개의 비밀번호가 일치합니다";
_text["Save"] = "저장";
_text["Save as default"] = "디폴트로 지정";
_text["Save order"] = "순서 저장";
_text["Saved"] = "저장하였습니다";
_text["Saving..."] = "저장중입니다...";
_text["School"] = "학교";
_text["School information deleted"] = "학교 정보가 삭제되었습니다";
_text["Schools"] = "학교정보";
_text["Search"] = "찾기";
_text["Search Friends"] = "친구찾기";
_text["Secede"] = "회원 탈퇴";
_text["See other"] = "사진 더보기";
_text["Select all"] = "전체 선택";
_text["Select blog"] = "블로그 선택";
_text["Select in entire network"] = "전체 친구목록에서 검색";
_text["Selection"] = "선택";
_text["Send"] = "전송";
_text["Send a note"] = "쪽지 보내기";
_text["Send a reply note"] = "답장 쓰기";
_text["Send email"] = "보내기";
_text["Send query"] = "문의하기";
_text["Sender"] = "보낸사람";
_text["Sent Date"] = "보낸 날짜";
_text["Sent User"] = "보낸 사람";
_text["Sent notes"] = "보낸 쪽지";
_text["Sent request"] = "보낸 신청";
_text["Session logged out by no interaction long time"] = "오랫동안 사용하지 않아 로그아웃되었습니다";
_text["Set as default"] = "기본 사진으로 설정";
_text["Set visitors logs"] = "방문 기록 설정";
_text["Set your password to enable <b>%s</b> as an OpenID<br />You can log in other relaying parties with <b>%s</b>"] = "<b>%s</b> 을 오픈아이디로 사용하시려면 아래 비밀번호를 설정해 주세요.<br />설정하신 후에는 <b>%s</b> 으로 다른 오픈아이디 지원 사이트들을 로그인하여 이용하실 수 있습니다";
_text["Setting IDtail api key"] = "아이디테일 Api key";
_text["Setting IDtail login bookmarklet"] = "아이디테일 로그인 북마클릿";
_text["Settings"] = "환경설정";
_text["Show another image"] = "다른 그림 보기";
_text["Show detail"] = "자세히보기";
_text["Show namecard"] = "명함보기";
_text["Show users of group"] = "그룹보기";
_text["Sign up"] = "회원가입";
_text["Signup date"] = "가입일";
_text["Site logo"] = "사이트 로고";
_text["Site management "] = "사이트 관리";
_text["Sorry, we logged off %s being logged in"] = "죄송합니다. 확인을 위해 로그인 되어 있던 %s를 로그아웃하였습니다";
_text["Status"] = "상태";
_text["Subject"] = "제목";
_text["Success"] = "수정되었습니다";
_text["Terms of service"] = "이용약관";
_text["Text must be lower than 10 characters"] = "지역명은 10자이내로 입력하세요";
_text["Textcube"] = "텍스트큐브";
_text["The requested address %s was not found on this server."] = "요청하신 '%s' 페이지를 찾을 수 없습니다";
_text["The uploaded file size is bigger than limit size"] = "업로드한 파일이 너무 큽니다";
_text["The uploaded file was only partially uploaded"] = "파일이 일부만 업로드되었습니다";
_text["There is no application profile page"] = "어플리케이션 페이지가 없습니다";
_text["There is no registered application"] = "등록된 마이템이 없습니다";
_text["There is no such pending information"] = "요청하신 승인 대기중인 항목이 없습니다.";
_text["This address is invalid"] = "유효하지 않은 주소입니다";
_text["This authentication will affects to %s"] = "본 로그인은 %s에만 영향을 미칩니다";
_text["This card is not public"] = "이 카드는 공개되어 있지 않습니다";
_text["This image type is not permitted"] = "지원하지 않는 형식입니다";
_text["This image will be shown up at login page and helps you to find whether this is right site"] = "<b>내가 직접 등록한 이미지와 문구</b>를 IDtail의 로그인 인증 페이지에서 확인함으로써,악의적인 피싱사이트의 <br />페이지와 구분할 수 있는 기능입니다.";
_text["This is private message"] = "비밀글입니다";
_text["This key is invalid."] = "유효하지 않은 접근입니다";
_text["This username can be used as openid"] = "등록하신 아이디는 오픈아이디로 사용하실 수 있습니다";
_text["This username is not available"] = "사용할 수 없는 ID 입니다";
_text["Tistory"] = "티스토리";
_text["Title"] = "직위";
_text["Too long to save"] = "너무 길어 저장할 수 없습니다";
_text["Too long username (Maximum: 20)"] = "아이디는 20자 이하입니다";
_text["Too short username (Minimum: 4)"] = "아이디는 4자 이상입니다";
_text["Trust"] = "승인";
_text["Trust this time only"] = "이번만 승인";
_text["Type as email format"] = "올바른 이메일 형식이 아닙니다";
_text["Type as openid format"] = "올바른 오픈아이디 형식이 아닙니다";
_text["URL of company"] = "회사 홈페이지";
_text["USA"] = "미국";
_text["UnAuthorized"] = "미인증";
_text["Unauthorized"] = "미인증";
_text["Unclassified"] = "미분류";
_text["Univ."] = "대학교";
_text["University/College"] = "대학(교)";
_text["Unknown system error"] = "알수없는 시스템 오류";
_text["Unread"] = "읽지 않음";
_text["Untrust"] = "승인 취소";
_text["Update failure"] = "업데이트 오류";
_text["Updated mytem"] = "업데이트 마이템";
_text["Upload"] = "업로드";
_text["Url"] = "Url";
_text["Use as OpenID"] = "오픈아이디로 사용";
_text["User not found"] = "사용자가 없습니다";
_text["Username and email doesn't matched"] = "입력하신 아이디에 해당하는 이메일이 없습니다";
_text["Verification cancelled"] = "인증을 취소하였습니다";
_text["Wait"] = "대기";
_text["We can't send mail"] = "메일을 보낼 수 없었습니다";
_text["We cannot find such a user"] = "이메일이 발견되지 않습니다";
_text["We did not send invitation to %d people"] = "%d 명의 수신자에게는 초대 메일을 보내지 않았습니다";
_text["We did not send invitation to a person"] = "1 명의 수신자에게는 초대 메일을 보내지 않았습니다";
_text["We have a problem in copying URL to clipboard"] = "URL을 클립보드에 복사하는 중에 오류가 발생하였습니다";
_text[""+"We sent a mail to <b>%s</b> to find your id\n"+"Occasionally this mail can not be deliverred and be classified as a spam"] = ""+"회원님의 메일 주소 <b>%s</b>으로 아이디 찾기를 위한 이메일이 전송되었습니다.<br />\n"+"일부 메일의 경우 스팸함으로 메일이 전송되는 경우가 있으니 수신 메일을 꼭 확인해주십시오";
_text[""+"We sent a mail to <b>%s</b> to reset your password\n"+"Occasionally this mail can not be deliverred and be classified as a spam"] = ""+"회원님의 개인정보 보호를 위해서 회원님의 메일 계정<br />\n"+"<b>%s</b>으로 비밀번호 초기화를 위한 이메일이 전송되었습니다.<br />일부 메일의 경우 스팸함으로 메일이 전송되는 경우가 있으니 수신 메일을 꼭 확인해주십시오.";
_text["Web service"] = "웹 서비스(RSS)";
_text["Web sites"] = "웹 사이트";
_text["Websites"] = "웹사이트";
_text["Welcome to IDtail, USERNAME!"] = "USERNAME님, 아이디테일 방문을 환영합니다";
_text["Welcome! %s supports OpenID."] = "%s는 OpenID를 지원합니다.";
_text["What is IDtail"] = "아이디테일 이야기";
_text["What is IDtail?"] = "아이디테일 이야기";
_text["Working period"] = "근무기간";
_text["Writer Photo"] = "작성자 사진";
_text["Writing Content"] = "내용 작성";
_text["Writing the email directly"] = "이메일 직접 입력";
_text["Wrong Access. Password is not encrypted."] = "잘못된 접근입니다. 비밀번호가 암호화되지 않았습니다";
_text["Yahoo blog"] = "야후 블로그";
_text["Year"] = "년";
_text["Yes, I will use safe login"] = "안전로그인 기능을 사용하겠습니다";
_text["You already requested network to He/She"] = "이미 이 사용자에게 친구신청을 했습니다";
_text["You are not network of this guy"] = "본 사용자와 친구 관계가 아닙니다";
_text["You are now connected with %s (%s)"] = "%s(%s)님과 친구 관계가 되었습니다";
_text["You are now in testing eh? Good luck~"] = "오호! 뭔가 테스트 중이신가요?";
_text["You are trying to login to <b>%s</b>"] = "현재 <b>%s</b>에 로그인 중입니다";
_text["You can build your network with who has same interestings"] = "관심분야를 등록하시면 같은 관심분야의 사람들을 찾아보고 친구를 맺으실 수 있습니다";
_text["You can copy HTML source below and use everywhere you want"] = "아래의 명함 소스를 여러분의 블로그 등 원하시는 곳에 활용해 보세요";
_text["You can crop your photo into thumbnail images in <b>Idtail</b>"] = "<b>IDtail</b>은 사진의 원하는 부분을 잘라서 편집할 수 있는 기능을 제공합니다";
_text["You can customize the settings of each profile explosure condition of application and delete it"] = "프로필노출 여부 및 내마이템 목록에서도 삭제하실 수 있습니다";
_text["You can edit contents in the preview card below, or Mydtail managing pages"] = "명함 내용 수정은 마이디테일 관리에서 하실 수 있습니다. 아래의 미리보기 영역에서 수정을 원하시는 항목을 클릭하세요";
_text["You can get a api key when you make a new application used of idtail api"] = "아이디테일의 오픈 API를 이용해 새로운 어플리케이션을 개발하실 때 필요한 사용자 키(Key)를 발급받으실 수 있습니다.";
_text["You can keep your mydtail profile within the session which is logged in with the added OpenIDs"] = "추가등록하신 오픈아이디로 로그인한 경우에도 동일한 마이디테일 정보를 유지하실 수 있습니다";
_text["You can retrieve your blog posts if blogs are registerred"] = "블로그를 등록하시면 블로그의 최근 포스트를 마이디테일에 불러오실 수 있습니다";
_text["You can search by company name, school name, location if you fill your information"] = "학교나 회사, 지역 정보를 입력하시면 학교동문, 회사 동료, 지역 사람들을 검색하실 수 있습니다";
_text["You can select several users in once by push Ctrl key"] = "Ctrl키를 누르면 여러사람을 선택할 수 있습니다";
_text["You can send this message to several your friends, when you seperate the string by ,[comma].[Allowed only 10 person]"] = "여러친구에게 보내실 때는 ,(콤마)로 구분하세요.(10명까지 가능)";
_text["You can set up what if it`s explosured or not in your profile with the exception of deletion"] = "삭제는 되지 않으며 프로필 노출 여부를 설정하실 수 있습니다";
_text["You can upload to 20 files with typeof JPG, PNG, GIF"] = "JPG, PNG, GIF파일을 20장까지 업로드 하실 수 있습니다.<br />업로드한 이미지는 가로 600px 크기의 JPG파일로 변환됩니다.";
_text["You can use your own OpenID with \"<span class=\"openid\">%s</span>\", this is now disabled and you can enable by click \"Enable OpenID\" button and set password. Even after enabling this OpenID, you can log in with IDtail currently using other site's OpenID"] = "<span class=\"openid\">%s</span> 을 오픈아이디로 이용하시려면 아래의 버튼을 클릭하여 사용하실 오픈아이디의 비밀번호를 설정해 주시면 됩니다. <br /> 설정하신 후에도 사용하시던 <b>다른 오픈아이디로 로그인하셔도 동일</b>하게 <br />IDtail을 이용하실 수 있습니다";
_text["You can't remove the application"] = "이 어플리케이션을 삭제할 수 없습니다.";
_text["You can`t add the applications more than %1 in your profile"] = "프로필에 %1개 이상의 어플리케이션을 추가할 수 없습니다.";
_text["You can`t added application more than %1 in one tab"] = "한 탭에 %1개 이상의 어플리케이션을 추가할 수 없습니다.";
_text["You canceled login IDtail"] = "IDtail 로그인을 취소하였습니다";
_text["You cannot invite yourself"] = "자신과는 친구를 맺을 수는 없습니다";
_text["You cannot make network with yourself"] = "자신과는 친구를 맺을 수는 없습니다";
_text["You cannot use '%s' as an OpenID to logon anther site. Click above 'Use as OpenID' link and set you own password to enable your OpenID"] = "'%s'은 현재 비밀번호가 설정되어 있지 않으므로, 오픈아이디로는 이용하실 수 없습니다.<br />위의 <b>'오픈아이디로 사용하기'</b> 버튼을 클릭하고 비밀번호를 설정하시면 오픈아이디로도<br />사용하실 수 있습니다.";
_text[""+"You chose to show your information only to your network\n"+"But no group is checked, are you sure?"] = ""+"친구 공개로 설정하셨으나 선택된 그룹이 없습니다.\n"+"계속하시겠습니까?";
_text["You did not agree EULA"] = "서비스 약관에 동의하셔야 회원가입이 가능합니다";
_text["You did not agree privacy protection policy"] = "개인정보 보호정책에 동의하셔야 회원가입이 가능합니다";
_text["You don't have permission"] = "접근이 불가능합니다";
_text["You must input the charater in English"] = "영문으로만 입력해 주세요";
_text["You must log in to send email invitation"] = "지인을 초대하시려면 로그인 하셔야 합니다";
_text["You need to sign-in"] = "로그인이 필요합니다";
_text["You should login for using this page"] = "이 페이지에 접근하려면 로그인을 해야합니다";
_text["You should select at least one person"] = "최소한 한 명은 선택해야합니다";
_text["You should upload images which is different from your icon"] = "마이디테일 페이지에 등록한 이미지와는<br /> 다른 이미지를 등록하시는 것이 좋습니다";
_text["Your name is posted by <a href=\"%3\">nametag</a> in %1's <a href=\"%2\">photo talk</a>"] = "%1님 <a href=\"%2\">포토앨범</a>에 <a href=\"%3\">네임태그</a>로 등록되셨습니다 ";
_text["Your username already existed"] = "아이디가 이미 존재합니다";
_text["Your valuation comment is added"] = "리뷰가 등록되었습니다";
_text["[Trust confirm] This site has asked us for confirmation of your identity url"] = "[승인 요청] 아래의 사이트를 신뢰하시면 로그인을 승인해 주십시요";
_text["add tab"] = "탭 추가";
_text["adding new application is fail"] = "어플리케이션을 추가하지 못했습니다.";
_text["already application is published"] = "이미 발행된 어플리케이션입니다.";
_text["application"] = "어플리케이션";
_text["application category is empty"] = "어플리케이션 카테고리가 비어있습니다.";
_text["application description is empty"] = "어플리케이션 설명이 없습니다.";
_text["application is already attached to your container"] = "컨테이너에 이미 어플리케이션이 등록되어 있습니다.";
_text["application is not exist"] = "어플리케이션이 존재하지 않습니다.";
_text["application name is empty"] = "어플리케이션 이름이 없습니다.";
_text["application publishing is success"] = "어플리케이션이 발행 되었습니다";
_text["application register form is empty"] = "어플리케이션 등록폼이 없습니다.";
_text["application source or url is empty"] = "어플리케이션 소스 또는 URL이 비어있습니다.";
_text["birthday"] = "생일";
_text["click the below button for generation the api key"] = "아래의 사용자 키(Key) 발급 버튼을 클릭하세요.";
_text["comment length is too long"] = "글이 너무 깁니다";
_text["contents is empty. Please fill in a blank"] = "내용이 비어있습니다. 빈 칸을 채워 주세요";
_text["default"] = "기본";
_text["description"] = "설명";
_text["directory"] = "디렉토리";
_text["edit"] = "편집";
_text["entranced"] = "입학";
_text["expires at %m-%d %H:%M"] = "로그인 만료시간: %m-%d %H:%M";
_text["failed to send a mail"] = "메일을 보낼 수 없었습니다";
_text["failure of adding new application"] = "어플리케이션 등록 실패";
_text["failure of removing a application"] = "어플리케이션 삭제 실패";
_text["failure of updating a application"] = "어플리케이션 업데이트 실패";
_text["graduated"] = "졸업";
_text["group name : %s is already exists"] = "이미 존재하는 그룹입니다: %s";
_text["guestbook"] = "방명록";
_text["icon"] = "아이콘";
_text["import is failed"] = "가져오기 실패";
_text["input the owner name"] = "사용자 이름을 입력하세요.";
_text["location text %s inserted to location field"] = "새로운 지역명(%s)이 추가되었습니다";
_text["location text deleted"] = "지역이 삭제되었습니다";
_text["location text deletion is failed"] = "지역을 삭제할 수 없습니다.";
_text["location text is empty. nothing to delete"] = "입력된 지역명이 없습니다. 삭제할 수 없습니다.";
_text["location text is saving..."] = "지역을 저장중입니다...";
_text["location text is too long"] = "지역명이 너무 깁니다";
_text["location text saved"] = "지역이 저장되었습니다";
_text["login"] = "로그인";
_text["login required for secede"] = "탈퇴하시려면 로그인을 해야합니다";
_text["logo"] = "로고";
_text["making a success of response "] = "성공하였습니다";
_text["maximum selectable number of invitation is 10"] = "최대 10명까지만 선택하실 수 있습니다";
_text["me2day"] = "미투데이";
_text["mydtail"] = "마이디테일";
_text["name"] = "이름";
_text["network"] = "친구";
_text["network request accepted"] = "친구신청 수락했습니다";
_text["network request did not send"] = "친구신청을 하지 못했습니다";
_text["network request rejected"] = "친구신청을 거절했습니다";
_text["network request sent"] = "친구신청을 했습니다";
_text["nickname"] = "닉네임";
_text["no Content"] = "내용 없음";
_text["not exist username"] = "존재하지 않는 사용자 입니다";
_text["not existed a application"] = "존재하지 않는 트랜잭션입니다.";
_text["not supported type"] = "지원하지 않는 형식입니다";
_text["note did not send"] = "쪽지를 보내지 못하였습니다.";
_text["note sent"] = "쪽지를 보냈습니다";
_text["openid_event"] = "오픈아이디 이벤트";
_text["permission denied"] = "권한이 없습니다";
_text["photo"] = "사진";
_text["please fill in a blank"] = "빈 칸을 채워 주세요";
_text["please fill the blanks"] = "빈 칸을 채워 주세요";
_text["please input the application id"] = "어플리케이션 ID를 입력해 주세요";
_text["please login with openid one more time"] = "오픈아이디로 한 번더 로그인하여 주세요";
_text["refresh"] = "새로고침";
_text["removing new application is fail"] = "어플리케이션 제거 실패";
_text["request a network"] = "친구 신청";
_text["requested network informed to administrator"] = "관리자에게 해당 신청을 신고하였습니다";
_text["require 1 parameter"] = "파라메터가 1개 필요합니다";
_text["require 2 parameters"] = "파라메터가 2개 필요합니다";
_text["require 3 parameters"] = "파라메터가 3개 필요합니다";
_text["require 4 parameters"] = "파라메터가 4개 필요합니다";
_text["require a parameter of the application id"] = "어플리케이션 ID가 파라메터로 필요합니다";
_text["require app_id parameter"] = "어플리케이션 아이디 파라메터가 필요합니다";
_text["require parameter of username"] = "파라메터로 사용자ID가 필요합니다";
_text["require search keyword"] = "검색 키워드를 입력하세요.";
_text["saved a new applicarion"] = "새로운 어플리케이션을 저장했습니다";
_text["tab is not exist"] = "탭이 존재하지 않습니다";
_text["the guestbook post has been deleted"] = "작성하신 글이 삭제되었습니다";
_text["this location is insertable"] = "저장 가능한 지역명입니다";
_text["this location text is already exists"] = "이 지역은 이미 등록되어 있습니다";
_text["this users are already networked"] = "이미 친구 관계입니다";
_text["this->uses is not array (occured from %s : %s)"] = "this->uses is not array (occured from %s : %s)";
_text["today(s)"] = "오늘";
_text["unAuthorized"] = "미인증";
_text["update application"] = "어플리케이션 업데이트";
_text["updating new application`s location  is fail"] = "어플리케이션의 위치를 변경할 수 없었습니다";
_text["yesterday(s)"] = "어제";
_text["you can not insert this location directly. choose again"] = "직접입력된 지역명으로는 저장되지 않습니다";
_text["you can't put the message which over 2000bytes"] = "1000자 이내로 작성해주세요";
_text["your api key is created"] = "Api key가 발급되었습니다.";
var _debug = 0;
function _(src)
{
if( src == undefined )
{
alert("ASSERT failure: undefined src is requested");
}
var st = _text[src];
if( st == "" )
{
st = src;
}
if( st == undefined )
{
if( _debug )
{
alert("ASSERT failure: " + src + " is not defined" );
return "TODO";
}
st = src;
}
if( _debug == 1 )
{
st = "CHECK2";
}
return st;
}
function __(src)
{
var st = _text[src];
if( st == "" )
{
st = src;
}
if( st == undefined )
{
if( _debug )
{
alert("ASSERT failure: " + src + " is not defined" );
document.write( "TODO" );
return;
}
st = src;
}
if( _debug == 1 )
{
st = "CHECK2";
}
document.write( st );
}
var Prototype = {
Version: '1.6.0.2',
Browser: {
IE:     !!(window.attachEvent && !window.opera),
Opera:  !!window.opera,
WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
},
BrowserFeatures: {
XPath: !!document.evaluate,
ElementExtensions: !!window.HTMLElement,
SpecificElementExtensions:
document.createElement('div').__proto__ &&
document.createElement('div').__proto__ !==
document.createElement('form').__proto__
},
ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
emptyFunction: function() { },
K: function(x) { return x }
};
if (Prototype.Browser.MobileSafari)
Prototype.BrowserFeatures.SpecificElementExtensions = false;
var Class = {
create: function() {
var parent = null, properties = $A(arguments);
if (Object.isFunction(properties[0]))
parent = properties.shift();
function klass() {
this.initialize.apply(this, arguments);
}
Object.extend(klass, Class.Methods);
klass.superclass = parent;
klass.subclasses = [];
if (parent) {
var subclass = function() { };
subclass.prototype = parent.prototype;
klass.prototype = new subclass;
parent.subclasses.push(klass);
}
for (var i = 0; i < properties.length; i++)
klass.addMethods(properties[i]);
if (!klass.prototype.initialize)
klass.prototype.initialize = Prototype.emptyFunction;
klass.prototype.constructor = klass;
return klass;
}
};
Class.Methods = {
addMethods: function(source) {
var ancestor   = this.superclass && this.superclass.prototype;
var properties = Object.keys(source);
if (!Object.keys({ toString: true }).length)
properties.push("toString", "valueOf");
for (var i = 0, length = properties.length; i < length; i++) {
var property = properties[i], value = source[property];
if (ancestor && Object.isFunction(value) &&
value.argumentNames().first() == "$super") {
var method = value, value = Object.extend((function(m) {
return function() { return ancestor[m].apply(this, arguments) };
})(property).wrap(method), {
valueOf:  function() { return method },
toString: function() { return method.toString() }
});
}
this.prototype[property] = value;
}
return this;
}
};
var Abstract = { };
Object.extend = function(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
};
Object.extend(Object, {
inspect: function(object) {
try {
if (Object.isUndefined(object)) return 'undefined';
if (object === null) return 'null';
return object.inspect ? object.inspect() : String(object);
} catch (e) {
if (e instanceof RangeError) return '...';
throw e;
}
},
toJSON: function(object) {
var type = typeof object;
switch (type) {
case 'undefined':
case 'function':
case 'unknown': return;
case 'boolean': return object.toString();
}
if (object === null) return 'null';
if (object.toJSON) return object.toJSON();
if (Object.isElement(object)) return;
var results = [];
for (var property in object) {
var value = Object.toJSON(object[property]);
if (!Object.isUndefined(value))
results.push(property.toJSON() + ': ' + value);
}
return '{' + results.join(', ') + '}';
},
toQueryString: function(object) {
return $H(object).toQueryString();
},
toHTML: function(object) {
return object && object.toHTML ? object.toHTML() : String.interpret(object);
},
keys: function(object) {
var keys = [];
for (var property in object)
keys.push(property);
return keys;
},
values: function(object) {
var values = [];
for (var property in object)
values.push(object[property]);
return values;
},
clone: function(object) {
return Object.extend({ }, object);
},
isElement: function(object) {
return object && object.nodeType == 1;
},
isArray: function(object) {
return object != null && typeof object == "object" &&
'splice' in object && 'join' in object;
},
isHash: function(object) {
return object instanceof Hash;
},
isFunction: function(object) {
return typeof object == "function";
},
isString: function(object) {
return typeof object == "string";
},
isNumber: function(object) {
return typeof object == "number";
},
isUndefined: function(object) {
return typeof object == "undefined";
}
});
Object.extend(Function.prototype, {
argumentNames: function() {
var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
return names.length == 1 && !names[0] ? [] : names;
},
bind: function() {
if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object, args.concat($A(arguments)));
}
},
bindAsEventListener: function() {
var __method = this, args = $A(arguments), object = args.shift();
return function(event) {
return __method.apply(object, [event || window.event].concat(args));
}
},
curry: function() {
if (!arguments.length) return this;
var __method = this, args = $A(arguments);
return function() {
return __method.apply(this, args.concat($A(arguments)));
}
},
delay: function() {
var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
return window.setTimeout(function() {
return __method.apply(__method, args);
}, timeout);
},
wrap: function(wrapper) {
var __method = this;
return function() {
return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
}
},
methodize: function() {
if (this._methodized) return this._methodized;
var __method = this;
return this._methodized = function() {
return __method.apply(null, [this].concat($A(arguments)));
};
}
});
Function.prototype.defer = Function.prototype.delay.curry(0.01);
Date.prototype.toJSON = function() {
return '"' + this.getUTCFullYear() + '-' +
(this.getUTCMonth() + 1).toPaddedString(2) + '-' +
this.getUTCDate().toPaddedString(2) + 'T' +
this.getUTCHours().toPaddedString(2) + ':' +
this.getUTCMinutes().toPaddedString(2) + ':' +
this.getUTCSeconds().toPaddedString(2) + 'Z"';
};
var Try = {
these: function() {
var returnValue;
for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
break;
} catch (e) { }
}
return returnValue;
}
};
RegExp.prototype.match = RegExp.prototype.test;
RegExp.escape = function(str) {
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
var PeriodicalExecuter = Class.create({
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;
this.registerCallback();
},
registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},
execute: function() {
this.callback(this);
},
stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},
onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
} finally {
this.currentlyExecuting = false;
}
}
}
});
Object.extend(String, {
interpret: function(value) {
return value == null ? '' : String(value);
},
specialChar: {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\\': '\\\\'
}
});
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
replacement = arguments.callee.prepareReplacement(replacement);
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
result += String.interpret(replacement(match));
source  = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
}
}
return result;
},
sub: function(pattern, replacement, count) {
replacement = this.gsub.prepareReplacement(replacement);
count = Object.isUndefined(count) ? 1 : count;
return this.gsub(pattern, function(match) {
if (--count < 0) return match[0];
return replacement(match);
});
},
scan: function(pattern, iterator) {
this.gsub(pattern, iterator);
return String(this);
},
truncate: function(length, truncation) {
length = length || 30;
truncation = Object.isUndefined(truncation) ? '...' : truncation;
return this.length > length ?
this.slice(0, length - truncation.length) + truncation : String(this);
},
strip: function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
},
stripTags: function() {
return this.replace(/<\/?[^>]+>/gi, '');
},
stripScripts: function() {
return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
},
extractScripts: function() {
var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
return (this.match(matchAll) || []).map(function(scriptTag) {
return (scriptTag.match(matchOne) || ['', ''])[1];
});
},
evalScripts: function() {
return this.extractScripts().map(function(script) { return eval(script) });
},
escapeHTML: function() {
var self = arguments.callee;
self.text.data = this;
return self.div.innerHTML;
},
unescapeHTML: function() {
var div = new Element('div');
div.innerHTML = this.stripTags();
return div.childNodes[0] ? (div.childNodes.length > 1 ?
$A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
div.childNodes[0].nodeValue) : '';
},
toQueryParams: function(separator) {
var match = this.strip().match(/([^?#]*)(#.*)?$/);
if (!match) return { };
return match[1].split(separator || '&').inject({ }, function(hash, pair) {
if ((pair = pair.split('='))[0]) {
var key = decodeURIComponent(pair.shift());
var value = pair.length > 1 ? pair.join('=') : pair[0];
if (value != undefined) value = decodeURIComponent(value);
if (key in hash) {
if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
hash[key].push(value);
}
else hash[key] = value;
}
return hash;
});
},
toArray: function() {
return this.split('');
},
succ: function() {
return this.slice(0, this.length - 1) +
String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
},
times: function(count) {
return count < 1 ? '' : new Array(count + 1).join(this);
},
camelize: function() {
var parts = this.split('-'), len = parts.length;
if (len == 1) return parts[0];
var camelized = this.charAt(0) == '-'
? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
: parts[0];
for (var i = 1; i < len; i++)
camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
return camelized;
},
capitalize: function() {
return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
},
underscore: function() {
return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
},
dasherize: function() {
return this.gsub(/_/,'-');
},
inspect: function(useDoubleQuotes) {
var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
var character = String.specialChar[match[0]];
return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
});
if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
return "'" + escapedString.replace(/'/g, '\\\'') + "'";
},
toJSON: function() {
return this.inspect(true);
},
unfilterJSON: function(filter) {
return this.sub(filter || Prototype.JSONFilter, '#{1}');
},
isJSON: function() {
var str = this;
if (str.blank()) return false;
str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
},
evalJSON: function(sanitize) {
var json = this.unfilterJSON();
try {
if (!sanitize || json.isJSON()) return eval('(' + json + ')');
} catch (e) { }
throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
},
include: function(pattern) {
return this.indexOf(pattern) > -1;
},
startsWith: function(pattern) {
return this.indexOf(pattern) === 0;
},
endsWith: function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
},
empty: function() {
return this == '';
},
blank: function() {
return /^\s*$/.test(this);
},
interpolate: function(object, pattern) {
return new Template(this, pattern).evaluate(object);
}
});
if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
escapeHTML: function() {
return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
},
unescapeHTML: function() {
return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
}
});
String.prototype.gsub.prepareReplacement = function(replacement) {
if (Object.isFunction(replacement)) return replacement;
var template = new Template(replacement);
return function(match) { return template.evaluate(match) };
};
String.prototype.parseQuery = String.prototype.toQueryParams;
Object.extend(String.prototype.escapeHTML, {
div:  document.createElement('div'),
text: document.createTextNode('')
});
with (String.prototype.escapeHTML) div.appendChild(text);
var Template = Class.create({
initialize: function(template, pattern) {
this.template = template.toString();
this.pattern = pattern || Template.Pattern;
},
evaluate: function(object) {
if (Object.isFunction(object.toTemplateReplacements))
object = object.toTemplateReplacements();
return this.template.gsub(this.pattern, function(match) {
if (object == null) return '';
var before = match[1] || '';
if (before == '\\') return match[2];
var ctx = object, expr = match[3];
var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
match = pattern.exec(expr);
if (match == null) return before;
while (match != null) {
var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
ctx = ctx[comp];
if (null == ctx || '' == match[3]) break;
expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
match = pattern.exec(expr);
}
return before + String.interpret(ctx);
});
}
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
var $break = { };
var Enumerable = {
each: function(iterator, context) {
var index = 0;
iterator = iterator.bind(context);
try {
this._each(function(value) {
iterator(value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
},
eachSlice: function(number, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var index = -number, slices = [], array = this.toArray();
while ((index += number) < array.length)
slices.push(array.slice(index, index+number));
return slices.collect(iterator, context);
},
all: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result = true;
this.each(function(value, index) {
result = result && !!iterator(value, index);
if (!result) throw $break;
});
return result;
},
any: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result = false;
this.each(function(value, index) {
if (result = !!iterator(value, index))
throw $break;
});
return result;
},
collect: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var results = [];
this.each(function(value, index) {
results.push(iterator(value, index));
});
return results;
},
detect: function(iterator, context) {
iterator = iterator.bind(context);
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
result = value;
throw $break;
}
});
return result;
},
findAll: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (iterator(value, index))
results.push(value);
});
return results;
},
grep: function(filter, iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var results = [];
if (Object.isString(filter))
filter = new RegExp(filter);
this.each(function(value, index) {
if (filter.match(value))
results.push(iterator(value, index));
});
return results;
},
include: function(object) {
if (Object.isFunction(this.indexOf))
if (this.indexOf(object) != -1) return true;
var found = false;
this.each(function(value) {
if (value == object) {
found = true;
throw $break;
}
});
return found;
},
inGroupsOf: function(number, fillWith) {
fillWith = Object.isUndefined(fillWith) ? null : fillWith;
return this.eachSlice(number, function(slice) {
while(slice.length < number) slice.push(fillWith);
return slice;
});
},
inject: function(memo, iterator, context) {
iterator = iterator.bind(context);
this.each(function(value, index) {
memo = iterator(memo, value, index);
});
return memo;
},
invoke: function(method) {
var args = $A(arguments).slice(1);
return this.map(function(value) {
return value[method].apply(value, args);
});
},
max: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
if (result == null || value >= result)
result = value;
});
return result;
},
min: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var result;
this.each(function(value, index) {
value = iterator(value, index);
if (result == null || value < result)
result = value;
});
return result;
},
partition: function(iterator, context) {
iterator = iterator ? iterator.bind(context) : Prototype.K;
var trues = [], falses = [];
this.each(function(value, index) {
(iterator(value, index) ?
trues : falses).push(value);
});
return [trues, falses];
},
pluck: function(property) {
var results = [];
this.each(function(value) {
results.push(value[property]);
});
return results;
},
reject: function(iterator, context) {
iterator = iterator.bind(context);
var results = [];
this.each(function(value, index) {
if (!iterator(value, index))
results.push(value);
});
return results;
},
sortBy: function(iterator, context) {
iterator = iterator.bind(context);
return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}).pluck('value');
},
toArray: function() {
return this.map();
},
zip: function() {
var iterator = Prototype.K, args = $A(arguments);
if (Object.isFunction(args.last()))
iterator = args.pop();
var collections = [this].concat(args).map($A);
return this.map(function(value, index) {
return iterator(collections.pluck(index));
});
},
size: function() {
return this.toArray().length;
},
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
};
Object.extend(Enumerable, {
map:     Enumerable.collect,
find:    Enumerable.detect,
select:  Enumerable.findAll,
filter:  Enumerable.findAll,
member:  Enumerable.include,
entries: Enumerable.toArray,
every:   Enumerable.all,
some:    Enumerable.any
});
function $A(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
if (Prototype.Browser.WebKit) {
$A = function(iterable) {
if (!iterable) return [];
if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
iterable.toArray) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
};
}
Array.from = $A;
Object.extend(Array.prototype, Enumerable);
if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;
Object.extend(Array.prototype, {
_each: function(iterator) {
for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
},
clear: function() {
this.length = 0;
return this;
},
first: function() {
return this[0];
},
last: function() {
return this[this.length - 1];
},
compact: function() {
return this.select(function(value) {
return value != null;
});
},
flatten: function() {
return this.inject([], function(array, value) {
return array.concat(Object.isArray(value) ?
value.flatten() : [value]);
});
},
without: function() {
var values = $A(arguments);
return this.select(function(value) {
return !values.include(value);
});
},
reverse: function(inline) {
return (inline !== false ? this : this.toArray())._reverse();
},
reduce: function() {
return this.length > 1 ? this : this[0];
},
uniq: function(sorted) {
return this.inject([], function(array, value, index) {
if (0 == index || (sorted ? array.last() != value : !array.include(value)))
array.push(value);
return array;
});
},
intersect: function(array) {
return this.uniq().findAll(function(item) {
return array.detect(function(value) { return item === value });
});
},
clone: function() {
return [].concat(this);
},
size: function() {
return this.length;
},
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
},
toJSON: function() {
var results = [];
this.each(function(object) {
var value = Object.toJSON(object);
if (!Object.isUndefined(value)) results.push(value);
});
return '[' + results.join(', ') + ']';
}
});
if (Object.isFunction(Array.prototype.forEach))
Array.prototype._each = Array.prototype.forEach;
if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
i || (i = 0);
var length = this.length;
if (i < 0) i = length + i;
for (; i < length; i++)
if (this[i] === item) return i;
return -1;
};
if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
var n = this.slice(0, i).reverse().indexOf(item);
return (n < 0) ? n : i - n - 1;
};
Array.prototype.toArray = Array.prototype.clone;
function $w(string) {
if (!Object.isString(string)) return [];
string = string.strip();
return string ? string.split(/\s+/) : [];
}
if (Prototype.Browser.Opera){
Array.prototype.concat = function() {
var array = [];
for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
for (var i = 0, length = arguments.length; i < length; i++) {
if (Object.isArray(arguments[i])) {
for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
array.push(arguments[i][j]);
} else {
array.push(arguments[i]);
}
}
return array;
};
}
Object.extend(Number.prototype, {
toColorPart: function() {
return this.toPaddedString(2, 16);
},
succ: function() {
return this + 1;
},
times: function(iterator) {
$R(0, this, true).each(iterator);
return this;
},
toPaddedString: function(length, radix) {
var string = this.toString(radix || 10);
return '0'.times(length - string.length) + string;
},
toJSON: function() {
return isFinite(this) ? this.toString() : 'null';
}
});
$w('abs round ceil floor').each(function(method){
Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
return new Hash(object);
};
var Hash = Class.create(Enumerable, (function() {
function toQueryPair(key, value) {
if (Object.isUndefined(value)) return key;
return key + '=' + encodeURIComponent(String.interpret(value));
}
return {
initialize: function(object) {
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
},
_each: function(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
set: function(key, value) {
return this._object[key] = value;
},
get: function(key) {
return this._object[key];
},
unset: function(key) {
var value = this._object[key];
delete this._object[key];
return value;
},
toObject: function() {
return Object.clone(this._object);
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
index: function(value) {
var match = this.detect(function(pair) {
return pair.value === value;
});
return match && match.key;
},
merge: function(object) {
return this.clone().update(object);
},
update: function(object) {
return new Hash(object).inject(this, function(result, pair) {
result.set(pair.key, pair.value);
return result;
});
},
toQueryString: function() {
return this.map(function(pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values))
return values.map(toQueryPair.curry(key)).join('&');
}
return toQueryPair(key, values);
}).join('&');
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
},
toJSON: function() {
return Object.toJSON(this.toObject());
},
clone: function() {
return new Hash(this);
}
}
})());
Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
initialize: function(start, end, exclusive) {
this.start = start;
this.end = end;
this.exclusive = exclusive;
},
_each: function(iterator) {
var value = this.start;
while (this.include(value)) {
iterator(value);
value = value.succ();
}
},
include: function(value) {
if (value < this.start)
return false;
if (this.exclusive)
return value < this.end;
return value <= this.end;
}
});
var $R = function(start, end, exclusive) {
return new ObjectRange(start, end, exclusive);
};
var Ajax = {
getTransport: function() {
return Try.these(
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject('Msxml2.XMLHTTP')},
function() {return new ActiveXObject('Microsoft.XMLHTTP')}
) || false;
},
activeRequestCount: 0
};
Ajax.Responders = {
responders: [],
_each: function(iterator) {
this.responders._each(iterator);
},
register: function(responder) {
if (!this.include(responder))
this.responders.push(responder);
},
unregister: function(responder) {
this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (Object.isFunction(responder[callback])) {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) { }
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate:   function() { Ajax.activeRequestCount++ },
onComplete: function() { Ajax.activeRequestCount-- }
});
Ajax.Base = Class.create({
initialize: function(options) {
this.options = {
method:       'post',
asynchronous: true,
contentType:  'application/x-www-form-urlencoded',
encoding:     'UTF-8',
parameters:   '',
evalJSON:     true,
evalJS:       true
};
Object.extend(this.options, options || { });
this.options.method = this.options.method.toLowerCase();
if (Object.isString(this.options.parameters))
this.options.parameters = this.options.parameters.toQueryParams();
else if (Object.isHash(this.options.parameters))
this.options.parameters = this.options.parameters.toObject();
}
});
Ajax.Request = Class.create(Ajax.Base, {
_complete: false,
initialize: function($super, url, options) {
$super(options);
this.transport = Ajax.getTransport();
this.request(url);
},
request: function(url) {
this.url = url;
this.method = this.options.method;
var params = Object.clone(this.options.parameters);
if (!['get', 'post'].include(this.method)) {
params['_method'] = this.method;
this.method = 'post';
}
this.parameters = params;
if (params = Object.toQueryString(params)) {
if (this.method == 'get')
this.url += (this.url.include('?') ? '&' : '?') + params;
else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params += '&_=';
}
try {
var response = new Ajax.Response(this);
if (this.options.onCreate) this.options.onCreate(response);
Ajax.Responders.dispatch('onCreate', this, response);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
}
catch (e) {
this.dispatchException(e);
}
},
onStateChange: function() {
var readyState = this.transport.readyState;
if (readyState > 1 && !((readyState == 4) && this._complete))
this.respondToReadyState(this.transport.readyState);
},
setRequestHeaders: function() {
var headers = {
'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
};
if (this.method == 'post') {
headers['Content-type'] = this.options.contentType +
(this.options.encoding ? '; charset=' + this.options.encoding : '');
if (this.transport.overrideMimeType &&
(navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
headers['Connection'] = 'close';
}
if (typeof this.options.requestHeaders == 'object') {
var extras = this.options.requestHeaders;
if (Object.isFunction(extras.push))
for (var i = 0, length = extras.length; i < length; i += 2)
headers[extras[i]] = extras[i+1];
else
$H(extras).each(function(pair) { headers[pair.key] = pair.value });
}
for (var name in headers)
this.transport.setRequestHeader(name, headers[name]);
},
success: function() {
var status = this.getStatus();
return !status || (status >= 200 && status < 300);
},
getStatus: function() {
try {
return this.transport.status || 0;
} catch (e) { return 0 }
},
respondToReadyState: function(readyState) {
var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);
if (state == 'Complete') {
try {
this._complete = true;
(this.options['on' + response.status]
|| this.options['on' + (this.success() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
var contentType = response.getHeader('Content-type');
if (this.options.evalJS == 'force'
|| (this.options.evalJS && this.isSameOrigin() && contentType
&& contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
this.evalResponse();
}
try {
(this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
} catch (e) {
this.dispatchException(e);
}
if (state == 'Complete') {
this.transport.onreadystatechange = Prototype.emptyFunction;
}
},
isSameOrigin: function() {
var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
protocol: location.protocol,
domain: document.domain,
port: location.port ? ':' + location.port : ''
}));
},
getHeader: function(name) {
try {
return this.transport.getResponseHeader(name) || null;
} catch (e) { return null }
},
evalResponse: function() {
try {
return eval((this.transport.responseText || '').unfilterJSON());
} catch (e) {
this.dispatchException(e);
}
},
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
}
});
Ajax.Request.Events =
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Response = Class.create({
initialize: function(request){
this.request = request;
var transport  = this.transport  = request.transport,
readyState = this.readyState = transport.readyState;
if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
this.status       = this.getStatus();
this.statusText   = this.getStatusText();
this.responseText = String.interpret(transport.responseText);
this.headerJSON   = this._getHeaderJSON();
}
if(readyState == 4) {
var xml = transport.responseXML;
this.responseXML  = Object.isUndefined(xml) ? null : xml;
this.responseJSON = this._getResponseJSON();
}
},
status:      0,
statusText: '',
getStatus: Ajax.Request.prototype.getStatus,
getStatusText: function() {
try {
return this.transport.statusText || '';
} catch (e) { return '' }
},
getHeader: Ajax.Request.prototype.getHeader,
getAllHeaders: function() {
try {
return this.getAllResponseHeaders();
} catch (e) { return null }
},
getResponseHeader: function(name) {
return this.transport.getResponseHeader(name);
},
getAllResponseHeaders: function() {
return this.transport.getAllResponseHeaders();
},
_getHeaderJSON: function() {
var json = this.getHeader('X-JSON');
if (!json) return null;
json = decodeURIComponent(escape(json));
try {
return json.evalJSON(this.request.options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
},
_getResponseJSON: function() {
var options = this.request.options;
if (!options.evalJSON || (options.evalJSON != 'force' &&
!(this.getHeader('Content-type') || '').include('application/json')) ||
this.responseText.blank())
return null;
try {
return this.responseText.evalJSON(options.sanitizeJSON ||
!this.request.isSameOrigin());
} catch (e) {
this.request.dispatchException(e);
}
}
});
Ajax.Updater = Class.create(Ajax.Request, {
initialize: function($super, container, url, options) {
this.container = {
success: (container.success || container),
failure: (container.failure || (container.success ? null : container))
};
options = Object.clone(options);
var onComplete = options.onComplete;
options.onComplete = (function(response, json) {
this.updateContent(response.responseText);
if (Object.isFunction(onComplete)) onComplete(response, json);
}).bind(this);
$super(url, options);
},
updateContent: function(responseText) {
var receiver = this.container[this.success() ? 'success' : 'failure'],
options = this.options;
if (!options.evalScripts) responseText = responseText.stripScripts();
if (receiver = $(receiver)) {
if (options.insertion) {
if (Object.isString(options.insertion)) {
var insertion = { }; insertion[options.insertion] = responseText;
receiver.insert(insertion);
}
else options.insertion(receiver, responseText);
}
else receiver.update(responseText);
}
}
});
Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
initialize: function($super, container, url, options) {
$super(options);
this.onComplete = this.options.onComplete;
this.frequency = (this.options.frequency || 2);
this.decay = (this.options.decay || 1);
this.updater = { };
this.container = container;
this.url = url;
this.start();
},
start: function() {
this.options.onComplete = this.updateComplete.bind(this);
this.onTimerEvent();
},
stop: function() {
this.updater.options.onComplete = undefined;
clearTimeout(this.timer);
(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
},
updateComplete: function(response) {
if (this.options.decay) {
this.decay = (response.responseText == this.lastText ?
this.decay * this.options.decay : 1);
this.lastText = response.responseText;
}
this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
},
onTimerEvent: function() {
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
if (Prototype.BrowserFeatures.XPath) {
document._getElementsByXPath = function(expression, parentElement) {
var results = [];
var query = document.evaluate(expression, $(parentElement) || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, length = query.snapshotLength; i < length; i++)
results.push(Element.extend(query.snapshotItem(i)));
return results;
};
}
if (!window.Node) var Node = { };
if (!Node.ELEMENT_NODE) {
Object.extend(Node, {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
});
}
(function() {
var element = this.Element;
this.Element = function(tagName, attributes) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
if (Prototype.Browser.IE && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
};
Object.extend(this.Element, element || { });
}).call(window);
Element.cache = { };
Element.Methods = {
visible: function(element) {
return $(element).style.display != 'none';
},
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
hide: function(element) {
$(element).style.display = 'none';
return element;
},
show: function(element) {
$(element).style.display = '';
return element;
},
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
update: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) return element.update().insert(content);
content = Object.toHTML(content);
element.innerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
},
replace: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
else if (!Object.isElement(content)) {
content = Object.toHTML(content);
var range = element.ownerDocument.createRange();
range.selectNode(element);
content.evalScripts.bind(content).defer();
content = range.createContextualFragment(content.stripScripts());
}
element.parentNode.replaceChild(content, element);
return element;
},
insert: function(element, insertions) {
element = $(element);
if (Object.isString(insertions) || Object.isNumber(insertions) ||
Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
insertions = {bottom:insertions};
var content, insert, tagName, childNodes;
for (var position in insertions) {
content  = insertions[position];
position = position.toLowerCase();
insert = Element._insertionTranslations[position];
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
insert(element, content);
continue;
}
content = Object.toHTML(content);
tagName = ((position == 'before' || position == 'after')
? element.parentNode : element).tagName.toUpperCase();
childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
if (position == 'top' || position == 'after') childNodes.reverse();
childNodes.each(insert.curry(element));
content.evalScripts.bind(content).defer();
}
return element;
},
wrap: function(element, wrapper, attributes) {
element = $(element);
if (Object.isElement(wrapper))
$(wrapper).writeAttribute(attributes || { });
else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
else wrapper = new Element('div', wrapper);
if (element.parentNode)
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return wrapper;
},
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(), attribute = pair.last();
var value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
recursivelyCollect: function(element, property) {
element = $(element);
var elements = [];
while (element = element[property])
if (element.nodeType == 1)
elements.push(Element.extend(element));
return elements;
},
ancestors: function(element) {
return $(element).recursivelyCollect('parentNode');
},
descendants: function(element) {
return $(element).select("*");
},
firstDescendant: function(element) {
element = $(element).firstChild;
while (element && element.nodeType != 1) element = element.nextSibling;
return $(element);
},
immediateDescendants: function(element) {
if (!(element = $(element).firstChild)) return [];
while (element && element.nodeType != 1) element = element.nextSibling;
if (element) return [element].concat($(element).nextSiblings());
return [];
},
previousSiblings: function(element) {
return $(element).recursivelyCollect('previousSibling');
},
nextSiblings: function(element) {
return $(element).recursivelyCollect('nextSibling');
},
siblings: function(element) {
element = $(element);
return element.previousSiblings().reverse().concat(element.nextSiblings());
},
match: function(element, selector) {
if (Object.isString(selector))
selector = new Selector(selector);
return selector.match($(element));
},
up: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(element.parentNode);
var ancestors = element.ancestors();
return Object.isNumber(expression) ? ancestors[expression] :
Selector.findElement(ancestors, expression, index);
},
down: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return element.firstDescendant();
return Object.isNumber(expression) ? element.descendants()[expression] :
element.select(expression)[index || 0];
},
previous: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
var previousSiblings = element.previousSiblings();
return Object.isNumber(expression) ? previousSiblings[expression] :
Selector.findElement(previousSiblings, expression, index);
},
next: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
var nextSiblings = element.nextSiblings();
return Object.isNumber(expression) ? nextSiblings[expression] :
Selector.findElement(nextSiblings, expression, index);
},
select: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element, args);
},
adjacent: function() {
var args = $A(arguments), element = $(args.shift());
return Selector.findChildElements(element.parentNode, args).without(element);
},
identify: function(element) {
element = $(element);
var id = element.readAttribute('id'), self = arguments.callee;
if (id) return id;
do { id = 'anonymous_element_' + self.counter++ } while ($(id));
element.writeAttribute('id', id);
return id;
},
readAttribute: function(element, name) {
element = $(element);
if (Prototype.Browser.IE) {
var t = Element._attributeTranslations.read;
if (t.values[name]) return t.values[name](element, name);
if (t.names[name]) name = t.names[name];
if (name.include(':')) {
return (!element.attributes || !element.attributes[name]) ? null :
element.attributes[name].value;
}
}
return element.getAttribute(name);
},
writeAttribute: function(element, name, value) {
element = $(element);
var attributes = { }, t = Element._attributeTranslations.write;
if (typeof name == 'object') attributes = name;
else attributes[name] = Object.isUndefined(value) ? true : value;
for (var attr in attributes) {
name = t.names[attr] || attr;
value = attributes[attr];
if (t.values[attr]) name = t.values[attr](element, value);
if (value === false || value === null)
element.removeAttribute(name);
else if (value === true)
element.setAttribute(name, name);
else element.setAttribute(name, value);
}
return element;
},
getHeight: function(element) {
return $(element).getDimensions().height;
},
getWidth: function(element) {
return $(element).getDimensions().width;
},
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className ||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
},
addClassName: function(element, className) {
if (!(element = $(element))) return;
if (!element.hasClassName(className))
element.className += (element.className ? ' ' : '') + className;
return element;
},
removeClassName: function(element, className) {
if (!(element = $(element))) return;
element.className = element.className.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
return element;
},
toggleClassName: function(element, className) {
if (!(element = $(element))) return;
return element[element.hasClassName(className) ?
'removeClassName' : 'addClassName'](className);
},
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
empty: function(element) {
return $(element).innerHTML.blank();
},
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
var originalAncestor = ancestor;
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) & 8) === 8;
if (element.sourceIndex && !Prototype.Browser.Opera) {
var e = element.sourceIndex, a = ancestor.sourceIndex,
nextAncestor = ancestor.nextSibling;
if (!nextAncestor) {
do { ancestor = ancestor.parentNode; }
while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
}
if (nextAncestor && nextAncestor.sourceIndex)
return (e > a && e < nextAncestor.sourceIndex);
}
while (element = element.parentNode)
if (element == originalAncestor) return true;
return false;
},
scrollTo: function(element) {
element = $(element);
var pos = element.cumulativeOffset();
window.scrollTo(pos[0], pos[1]);
return element;
},
getStyle: function(element, style) {
element = $(element);
style = style == 'float' ? 'cssFloat' : style.camelize();
var value = element.style[style];
if (!value) {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity') return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
},
getOpacity: function(element) {
return $(element).getStyle('opacity');
},
setStyle: function(element, styles) {
element = $(element);
var elementStyle = element.style, match;
if (Object.isString(styles)) {
element.style.cssText += ';' + styles;
return styles.include('opacity') ?
element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
}
for (var property in styles)
if (property == 'opacity') element.setOpacity(styles[property]);
else {
try{
elementStyle[(property == 'float' || property == 'cssFloat') ?
(Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
property] = styles[property];
} catch(e){}
}
return element;
},
setOpacity: function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
return element;
},
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
if (window.opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
makeClipping: function(element) {
element = $(element);
if (element._overflow) return element;
element._overflow = Element.getStyle(element, 'overflow') || 'auto';
if (element._overflow !== 'hidden')
element.style.overflow = 'hidden';
return element;
},
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
},
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
},
positionedOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
if (element.tagName == 'BODY') break;
var p = Element.getStyle(element, 'position');
if (p !== 'static') break;
}
} while (element);
return Element._returnOffset(valueL, valueT);
},
absolutize: function(element) {
element = $(element);
if (element.getStyle('position') == 'absolute') return;
var offsets = element.positionedOffset();
var top     = offsets[1];
var left    = offsets[0];
var width   = element.clientWidth;
var height  = element.clientHeight;
element._originalLeft   = left - parseFloat(element.style.left  || 0);
element._originalTop    = top  - parseFloat(element.style.top || 0);
element._originalWidth  = element.style.width;
element._originalHeight = element.style.height;
element.style.position = 'absolute';
element.style.top    = top + 'px';
element.style.left   = left + 'px';
element.style.width  = width + 'px';
element.style.height = height + 'px';
return element;
},
relativize: function(element) {
element = $(element);
if (element.getStyle('position') == 'relative') return;
element.style.position = 'relative';
var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);
element.style.top    = top + 'px';
element.style.left   = left + 'px';
element.style.height = element._originalHeight;
element.style.width  = element._originalWidth;
return element;
},
cumulativeScrollOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.scrollTop  || 0;
valueL += element.scrollLeft || 0;
element = element.parentNode;
} while (element);
return Element._returnOffset(valueL, valueT);
},
getOffsetParent: function(element) {
if (element.offsetParent) return $(element.offsetParent);
if (element == document.body) return $(element);
while ((element = element.parentNode) && element != document.body)
if (Element.getStyle(element, 'position') != 'static')
return $(element);
return $(document.body);
},
viewportOffset: function(forElement) {
var valueT = 0, valueL = 0;
var element = forElement;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body &&
Element.getStyle(element, 'position') == 'absolute') break;
} while (element = element.offsetParent);
element = forElement;
do {
if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
valueT -= element.scrollTop  || 0;
valueL -= element.scrollLeft || 0;
}
} while (element = element.parentNode);
return Element._returnOffset(valueL, valueT);
},
clonePosition: function(element, source) {
var options = Object.extend({
setLeft:    true,
setTop:     true,
setWidth:   true,
setHeight:  true,
offsetTop:  0,
offsetLeft: 0
}, arguments[2] || { });
source = $(source);
var p = source.viewportOffset();
element = $(element);
var delta = [0, 0];
var parent = null;
if (Element.getStyle(element, 'position') == 'absolute') {
parent = element.getOffsetParent();
delta = parent.viewportOffset();
}
if (parent == document.body) {
delta[0] -= document.body.offsetLeft;
delta[1] -= document.body.offsetTop;
}
if (options.setLeft)   element.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
if (options.setTop)    element.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
if (options.setWidth)  element.style.width = source.offsetWidth + 'px';
if (options.setHeight) element.style.height = source.offsetHeight + 'px';
return element;
}
};
Element.Methods.identify.counter = 1;
Object.extend(Element.Methods, {
getElementsBySelector: Element.Methods.select,
childElements: Element.Methods.immediateDescendants
});
Element._attributeTranslations = {
write: {
names: {
className: 'class',
htmlFor:   'for'
},
values: { }
}
};
if (Prototype.Browser.Opera) {
Element.Methods.getStyle = Element.Methods.getStyle.wrap(
function(proceed, element, style) {
switch (style) {
case 'left': case 'top': case 'right': case 'bottom':
if (proceed(element, 'position') === 'static') return null;
case 'height': case 'width':
if (!Element.visible(element)) return null;
var dim = parseInt(proceed(element, style), 10);
if (dim !== element['offset' + style.capitalize()])
return dim + 'px';
var properties;
if (style === 'height') {
properties = ['border-top-width', 'padding-top',
'padding-bottom', 'border-bottom-width'];
}
else {
properties = ['border-left-width', 'padding-left',
'padding-right', 'border-right-width'];
}
return properties.inject(dim, function(memo, property) {
var val = proceed(element, property);
return val === null ? memo : memo - parseInt(val, 10);
}) + 'px';
default: return proceed(element, style);
}
}
);
Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
function(proceed, element, attribute) {
if (attribute === 'title') return element.title;
return proceed(element, attribute);
}
);
}
else if (Prototype.Browser.IE) {
Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
function(proceed, element) {
element = $(element);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
$w('positionedOffset viewportOffset').each(function(method) {
Element.Methods[method] = Element.Methods[method].wrap(
function(proceed, element) {
element = $(element);
var position = element.getStyle('position');
if (position !== 'static') return proceed(element);
var offsetParent = element.getOffsetParent();
if (offsetParent && offsetParent.getStyle('position') === 'fixed')
offsetParent.setStyle({ zoom: 1 });
element.setStyle({ position: 'relative' });
var value = proceed(element);
element.setStyle({ position: position });
return value;
}
);
});
Element.Methods.getStyle = function(element, style) {
element = $(element);
style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
var value = element.style[style];
if (!value && element.currentStyle) value = element.currentStyle[style];
if (style == 'opacity') {
if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
if (value[1]) return parseFloat(value[1]) / 100;
return 1.0;
}
if (value == 'auto') {
if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
return element['offset' + style.capitalize()] + 'px';
return null;
}
return value;
};
Element.Methods.setOpacity = function(element, value) {
function stripAlpha(filter){
return filter.replace(/alpha\([^\)]*\)/gi,'');
}
element = $(element);
var currentStyle = element.currentStyle;
if ((currentStyle && !currentStyle.hasLayout) ||
(!currentStyle && element.style.zoom == 'normal'))
element.style.zoom = 1;
var filter = element.getStyle('filter'), style = element.style;
if (value == 1 || value === '') {
(filter = stripAlpha(filter)) ?
style.filter = filter : style.removeAttribute('filter');
return element;
} else if (value < 0.00001) value = 0;
style.filter = stripAlpha(filter) +
'alpha(opacity=' + (value * 100) + ')';
return element;
};
Element._attributeTranslations = {
read: {
names: {
'class': 'className',
'for':   'htmlFor'
},
values: {
_getAttr: function(element, attribute) {
return element.getAttribute(attribute, 2);
},
_getAttrNode: function(element, attribute) {
var node = element.getAttributeNode(attribute);
return node ? node.value : "";
},
_getEv: function(element, attribute) {
attribute = element.getAttribute(attribute);
return attribute ? attribute.toString().slice(23, -2) : null;
},
_flag: function(element, attribute) {
return $(element).hasAttribute(attribute) ? attribute : null;
},
style: function(element) {
return element.style.cssText.toLowerCase();
},
title: function(element) {
return element.title;
}
}
}
};
Element._attributeTranslations.write = {
names: Object.extend({
cellpadding: 'cellPadding',
cellspacing: 'cellSpacing'
}, Element._attributeTranslations.read.names),
values: {
checked: function(element, value) {
element.checked = !!value;
},
style: function(element, value) {
element.style.cssText = value ? value : '';
}
}
};
Element._attributeTranslations.has = {};
$w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
'encType maxLength readOnly longDesc').each(function(attr) {
Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
Element._attributeTranslations.has[attr.toLowerCase()] = attr;
});
(function(v) {
Object.extend(v, {
href:        v._getAttr,
src:         v._getAttr,
type:        v._getAttr,
action:      v._getAttrNode,
disabled:    v._flag,
checked:     v._flag,
readonly:    v._flag,
multiple:    v._flag,
onload:      v._getEv,
onunload:    v._getEv,
onclick:     v._getEv,
ondblclick:  v._getEv,
onmousedown: v._getEv,
onmouseup:   v._getEv,
onmouseover: v._getEv,
onmousemove: v._getEv,
onmouseout:  v._getEv,
onfocus:     v._getEv,
onblur:      v._getEv,
onkeypress:  v._getEv,
onkeydown:   v._getEv,
onkeyup:     v._getEv,
onsubmit:    v._getEv,
onreset:     v._getEv,
onselect:    v._getEv,
onchange:    v._getEv
});
})(Element._attributeTranslations.read.values);
}
else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1) ? 0.999999 :
(value === '') ? '' : (value < 0.00001) ? 0 : value;
return element;
};
}
else if (Prototype.Browser.WebKit) {
Element.Methods.setOpacity = function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
if (value == 1)
if(element.tagName == 'IMG' && element.width) {
element.width++; element.width--;
} else try {
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch (e) { }
return element;
};
Element.Methods.cumulativeOffset = function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop  || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (Element.getStyle(element, 'position') == 'absolute') break;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
};
}
if (Prototype.Browser.IE || Prototype.Browser.Opera) {
Element.Methods.update = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) return element.update().insert(content);
content = Object.toHTML(content);
var tagName = element.tagName.toUpperCase();
if (tagName in Element._insertionTranslations.tags) {
$A(element.childNodes).each(function(node) { element.removeChild(node) });
Element._getContentFromAnonymousElement(tagName, content.stripScripts())
.each(function(node) { element.appendChild(node) });
}
else element.innerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
if ('outerHTML' in document.createElement('div')) {
Element.Methods.replace = function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
element.parentNode.replaceChild(content, element);
return element;
}
content = Object.toHTML(content);
var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
if (Element._insertionTranslations.tags[tagName]) {
var nextSibling = element.next();
var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
parent.removeChild(element);
if (nextSibling)
fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
else
fragments.each(function(node) { parent.appendChild(node) });
}
else element.outerHTML = content.stripScripts();
content.evalScripts.bind(content).defer();
return element;
};
}
Element._returnOffset = function(l, t) {
var result = [l, t];
result.left = l;
result.top = t;
return result;
};
Element._getContentFromAnonymousElement = function(tagName, html) {
var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
if (t) {
div.innerHTML = t[0] + html + t[1];
t[2].times(function() { div = div.firstChild });
} else div.innerHTML = html;
return $A(div.childNodes);
};
Element._insertionTranslations = {
before: function(element, node) {
element.parentNode.insertBefore(node, element);
},
top: function(element, node) {
element.insertBefore(node, element.firstChild);
},
bottom: function(element, node) {
element.appendChild(node);
},
after: function(element, node) {
element.parentNode.insertBefore(node, element.nextSibling);
},
tags: {
TABLE:  ['<table>',                '</table>',                   1],
TBODY:  ['<table><tbody>',         '</tbody></table>',           2],
TR:     ['<table><tbody><tr>',     '</tr></tbody></table>',      3],
TD:     ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
SELECT: ['<select>',               '</select>',                  1]
}
};
(function() {
Object.extend(this.tags, {
THEAD: this.tags.TBODY,
TFOOT: this.tags.TBODY,
TH:    this.tags.TD
});
}).call(Element._insertionTranslations);
Element.Methods.Simulated = {
hasAttribute: function(element, attribute) {
attribute = Element._attributeTranslations.has[attribute] || attribute;
var node = $(element).getAttributeNode(attribute);
return node && node.specified;
}
};
Element.Methods.ByTag = { };
Object.extend(Element, Element.Methods);
if (!Prototype.BrowserFeatures.ElementExtensions &&
document.createElement('div').__proto__) {
window.HTMLElement = { };
window.HTMLElement.prototype = document.createElement('div').__proto__;
Prototype.BrowserFeatures.ElementExtensions = true;
}
Element.extend = (function() {
if (Prototype.BrowserFeatures.SpecificElementExtensions)
return Prototype.K;
var Methods = { }, ByTag = Element.Methods.ByTag;
var extend = Object.extend(function(element) {
if (!element || element._extendedByPrototype ||
element.nodeType != 1 || element == window) return element;
var methods = Object.clone(Methods),
tagName = element.tagName, property, value;
if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);
for (property in methods) {
value = methods[property];
if (Object.isFunction(value) && !(property in element))
element[property] = value.methodize();
}
element._extendedByPrototype = Prototype.emptyFunction;
return element;
}, {
refresh: function() {
if (!Prototype.BrowserFeatures.ElementExtensions) {
Object.extend(Methods, Element.Methods);
Object.extend(Methods, Element.Methods.Simulated);
}
}
});
extend.refresh();
return extend;
})();
Element.hasAttribute = function(element, attribute) {
if (element.hasAttribute) return element.hasAttribute(attribute);
return Element.Methods.Simulated.hasAttribute(element, attribute);
};
Element.addMethods = function(methods) {
var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;
if (!methods) {
Object.extend(Form, Form.Methods);
Object.extend(Form.Element, Form.Element.Methods);
Object.extend(Element.Methods.ByTag, {
"FORM":     Object.clone(Form.Methods),
"INPUT":    Object.clone(Form.Element.Methods),
"SELECT":   Object.clone(Form.Element.Methods),
"TEXTAREA": Object.clone(Form.Element.Methods)
});
}
if (arguments.length == 2) {
var tagName = methods;
methods = arguments[1];
}
if (!tagName) Object.extend(Element.Methods, methods || { });
else {
if (Object.isArray(tagName)) tagName.each(extend);
else extend(tagName);
}
function extend(tagName) {
tagName = tagName.toUpperCase();
if (!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName] = { };
Object.extend(Element.Methods.ByTag[tagName], methods);
}
function copy(methods, destination, onlyIfAbsent) {
onlyIfAbsent = onlyIfAbsent || false;
for (var property in methods) {
var value = methods[property];
if (!Object.isFunction(value)) continue;
if (!onlyIfAbsent || !(property in destination))
destination[property] = value.methodize();
}
}
function findDOMClass(tagName) {
var klass;
var trans = {
"OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
"FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
"DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
"H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
"INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
"TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
"TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
"TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
"FrameSet", "IFRAME": "IFrame"
};
if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName + 'Element';
if (window[klass]) return window[klass];
klass = 'HTML' + tagName.capitalize() + 'Element';
if (window[klass]) return window[klass];
window[klass] = { };
window[klass].prototype = document.createElement(tagName).__proto__;
return window[klass];
}
if (F.ElementExtensions) {
copy(Element.Methods, HTMLElement.prototype);
copy(Element.Methods.Simulated, HTMLElement.prototype, true);
}
if (F.SpecificElementExtensions) {
for (var tag in Element.Methods.ByTag) {
var klass = findDOMClass(tag);
if (Object.isUndefined(klass)) continue;
copy(T[tag], klass.prototype);
}
}
Object.extend(Element, Element.Methods);
delete Element.ByTag;
if (Element.extend.refresh) Element.extend.refresh();
Element.cache = { };
};
document.viewport = {
getDimensions: function() {
var dimensions = { };
var B = Prototype.Browser;
$w('width height').each(function(d) {
var D = d.capitalize();
dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
(B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
});
return dimensions;
},
getWidth: function() {
return this.getDimensions().width;
},
getHeight: function() {
return this.getDimensions().height;
},
getScrollOffsets: function() {
return Element._returnOffset(
window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
}
};
var Selector = Class.create({
initialize: function(expression) {
this.expression = expression.strip();
this.compileMatcher();
},
shouldUseXPath: function() {
if (!Prototype.BrowserFeatures.XPath) return false;
var e = this.expression;
if (Prototype.Browser.WebKit &&
(e.include("-of-type") || e.include(":empty")))
return false;
if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
return false;
return true;
},
compileMatcher: function() {
if (this.shouldUseXPath())
return this.compileXPathMatcher();
var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
c = Selector.criteria, le, p, m;
if (Selector._cache[e]) {
this.matcher = Selector._cache[e];
return;
}
this.matcher = ["this.matcher = function(root) {",
"var r = root, h = Selector.handlers, c = false, n;"];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
p = ps[i];
if (m = e.match(p)) {
this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
new Template(c[i]).evaluate(m));
e = e.replace(m[0], '');
break;
}
}
}
this.matcher.push("return h.unique(n);\n}");
eval(this.matcher.join('\n'));
Selector._cache[this.expression] = this.matcher;
},
compileXPathMatcher: function() {
var e = this.expression, ps = Selector.patterns,
x = Selector.xpath, le, m;
if (Selector._cache[e]) {
this.xpath = Selector._cache[e]; return;
}
this.matcher = ['.//*'];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
if (m = e.match(ps[i])) {
this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
new Template(x[i]).evaluate(m));
e = e.replace(m[0], '');
break;
}
}
}
this.xpath = this.matcher.join('');
Selector._cache[this.expression] = this.xpath;
},
findElements: function(root) {
root = root || document;
if (this.xpath) return document._getElementsByXPath(this.xpath, root);
return this.matcher(root);
},
match: function(element) {
this.tokens = [];
var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
var le, p, m;
while (e && le !== e && (/\S/).test(e)) {
le = e;
for (var i in ps) {
p = ps[i];
if (m = e.match(p)) {
if (as[i]) {
this.tokens.push([i, Object.clone(m)]);
e = e.replace(m[0], '');
} else {
return this.findElements(document).include(element);
}
}
}
}
var match = true, name, matches;
for (var i = 0, token; token = this.tokens[i]; i++) {
name = token[0], matches = token[1];
if (!Selector.assertions[name](element, matches)) {
match = false; break;
}
}
return match;
},
toString: function() {
return this.expression;
},
inspect: function() {
return "#<Selector:" + this.expression.inspect() + ">";
}
});
Object.extend(Selector, {
_cache: { },
xpath: {
descendant:   "//*",
child:        "/*",
adjacent:     "/following-sibling::*[1]",
laterSibling: '/following-sibling::*',
tagName:      function(m) {
if (m[1] == '*') return '';
return "[local-name()='" + m[1].toLowerCase() +
"' or local-name()='" + m[1].toUpperCase() + "']";
},
className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
id:           "[@id='#{1}']",
attrPresence: function(m) {
m[1] = m[1].toLowerCase();
return new Template("[@#{1}]").evaluate(m);
},
attr: function(m) {
m[1] = m[1].toLowerCase();
m[3] = m[5] || m[6];
return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
},
pseudo: function(m) {
var h = Selector.xpath.pseudos[m[1]];
if (!h) return '';
if (Object.isFunction(h)) return h(m);
return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
},
operators: {
'=':  "[@#{1}='#{3}']",
'!=': "[@#{1}!='#{3}']",
'^=': "[starts-with(@#{1}, '#{3}')]",
'$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
'*=': "[contains(@#{1}, '#{3}')]",
'~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
'|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
},
pseudos: {
'first-child': '[not(preceding-sibling::*)]',
'last-child':  '[not(following-sibling::*)]',
'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
'checked':     "[@checked]",
'disabled':    "[@disabled]",
'enabled':     "[not(@disabled)]",
'not': function(m) {
var e = m[6], p = Selector.patterns,
x = Selector.xpath, le, v;
var exclusion = [];
while (e && le != e && (/\S/).test(e)) {
le = e;
for (var i in p) {
if (m = e.match(p[i])) {
v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
exclusion.push("(" + v.substring(1, v.length - 1) + ")");
e = e.replace(m[0], '');
break;
}
}
}
return "[not(" + exclusion.join(" and ") + ")]";
},
'nth-child':      function(m) {
return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
},
'nth-last-child': function(m) {
return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
},
'nth-of-type':    function(m) {
return Selector.xpath.pseudos.nth("position() ", m);
},
'nth-last-of-type': function(m) {
return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
},
'first-of-type':  function(m) {
m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
},
'last-of-type':   function(m) {
m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
},
'only-of-type':   function(m) {
var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
},
nth: function(fragment, m) {
var mm, formula = m[6], predicate;
if (formula == 'even') formula = '2n+0';
if (formula == 'odd')  formula = '2n+1';
if (mm = formula.match(/^(\d+)$/)) // digit only
return '[' + fragment + "= " + mm[1] + ']';
if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
if (mm[1] == "-") mm[1] = -1;
var a = mm[1] ? Number(mm[1]) : 1;
var b = mm[2] ? Number(mm[2]) : 0;
predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
"((#{fragment} - #{b}) div #{a} >= 0)]";
return new Template(predicate).evaluate({
fragment: fragment, a: a, b: b });
}
}
}
},
criteria: {
tagName:      'n = h.tagName(n, r, "#{1}", c);      c = false;',
className:    'n = h.className(n, r, "#{1}", c);    c = false;',
id:           'n = h.id(n, r, "#{1}", c);           c = false;',
attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
attr: function(m) {
m[3] = (m[5] || m[6]);
return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
},
pseudo: function(m) {
if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
},
descendant:   'c = "descendant";',
child:        'c = "child";',
adjacent:     'c = "adjacent";',
laterSibling: 'c = "laterSibling";'
},
patterns: {
laterSibling: /^\s*~\s*/,
child:        /^\s*>\s*/,
adjacent:     /^\s*\+\s*/,
descendant:   /^\s/,
tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
id:           /^#([\w\-\*]+)(\b|$)/,
className:    /^\.([\w\-\*]+)(\b|$)/,
pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
attrPresence: /^\[([\w]+)\]/,
attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
},
assertions: {
tagName: function(element, matches) {
return matches[1].toUpperCase() == element.tagName.toUpperCase();
},
className: function(element, matches) {
return Element.hasClassName(element, matches[1]);
},
id: function(element, matches) {
return element.id === matches[1];
},
attrPresence: function(element, matches) {
return Element.hasAttribute(element, matches[1]);
},
attr: function(element, matches) {
var nodeValue = Element.readAttribute(element, matches[1]);
return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
}
},
handlers: {
concat: function(a, b) {
for (var i = 0, node; node = b[i]; i++)
a.push(node);
return a;
},
mark: function(nodes) {
var _true = Prototype.emptyFunction;
for (var i = 0, node; node = nodes[i]; i++)
node._countedByPrototype = _true;
return nodes;
},
unmark: function(nodes) {
for (var i = 0, node; node = nodes[i]; i++)
node._countedByPrototype = undefined;
return nodes;
},
index: function(parentNode, reverse, ofType) {
parentNode._countedByPrototype = Prototype.emptyFunction;
if (reverse) {
for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
var node = nodes[i];
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
}
} else {
for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
}
},
unique: function(nodes) {
if (nodes.length == 0) return nodes;
var results = [], n;
for (var i = 0, l = nodes.length; i < l; i++)
if (!(n = nodes[i])._countedByPrototype) {
n._countedByPrototype = Prototype.emptyFunction;
results.push(Element.extend(n));
}
return Selector.handlers.unmark(results);
},
descendant: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
h.concat(results, node.getElementsByTagName('*'));
return results;
},
child: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++) {
for (var j = 0, child; child = node.childNodes[j]; j++)
if (child.nodeType == 1 && child.tagName != '!') results.push(child);
}
return results;
},
adjacent: function(nodes) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
var next = this.nextElementSibling(node);
if (next) results.push(next);
}
return results;
},
laterSibling: function(nodes) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
h.concat(results, Element.nextSiblings(node));
return results;
},
nextElementSibling: function(node) {
while (node = node.nextSibling)
if (node.nodeType == 1) return node;
return null;
},
previousElementSibling: function(node) {
while (node = node.previousSibling)
if (node.nodeType == 1) return node;
return null;
},
tagName: function(nodes, root, tagName, combinator) {
var uTagName = tagName.toUpperCase();
var results = [], h = Selector.handlers;
if (nodes) {
if (combinator) {
if (combinator == "descendant") {
for (var i = 0, node; node = nodes[i]; i++)
h.concat(results, node.getElementsByTagName(tagName));
return results;
} else nodes = this[combinator](nodes);
if (tagName == "*") return nodes;
}
for (var i = 0, node; node = nodes[i]; i++)
if (node.tagName.toUpperCase() === uTagName) results.push(node);
return results;
} else return root.getElementsByTagName(tagName);
},
id: function(nodes, root, id, combinator) {
var targetNode = $(id), h = Selector.handlers;
if (!targetNode) return [];
if (!nodes && root == document) return [targetNode];
if (nodes) {
if (combinator) {
if (combinator == 'child') {
for (var i = 0, node; node = nodes[i]; i++)
if (targetNode.parentNode == node) return [targetNode];
} else if (combinator == 'descendant') {
for (var i = 0, node; node = nodes[i]; i++)
if (Element.descendantOf(targetNode, node)) return [targetNode];
} else if (combinator == 'adjacent') {
for (var i = 0, node; node = nodes[i]; i++)
if (Selector.handlers.previousElementSibling(targetNode) == node)
return [targetNode];
} else nodes = h[combinator](nodes);
}
for (var i = 0, node; node = nodes[i]; i++)
if (node == targetNode) return [targetNode];
return [];
}
return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
},
className: function(nodes, root, className, combinator) {
if (nodes && combinator) nodes = this[combinator](nodes);
return Selector.handlers.byClassName(nodes, root, className);
},
byClassName: function(nodes, root, className) {
if (!nodes) nodes = Selector.handlers.descendant([root]);
var needle = ' ' + className + ' ';
for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
nodeClassName = node.className;
if (nodeClassName.length == 0) continue;
if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
results.push(node);
}
return results;
},
attrPresence: function(nodes, root, attr, combinator) {
if (!nodes) nodes = root.getElementsByTagName("*");
if (nodes && combinator) nodes = this[combinator](nodes);
var results = [];
for (var i = 0, node; node = nodes[i]; i++)
if (Element.hasAttribute(node, attr)) results.push(node);
return results;
},
attr: function(nodes, root, attr, value, operator, combinator) {
if (!nodes) nodes = root.getElementsByTagName("*");
if (nodes && combinator) nodes = this[combinator](nodes);
var handler = Selector.operators[operator], results = [];
for (var i = 0, node; node = nodes[i]; i++) {
var nodeValue = Element.readAttribute(node, attr);
if (nodeValue === null) continue;
if (handler(nodeValue, value)) results.push(node);
}
return results;
},
pseudo: function(nodes, name, value, root, combinator) {
if (nodes && combinator) nodes = this[combinator](nodes);
if (!nodes) nodes = root.getElementsByTagName("*");
return Selector.pseudos[name](nodes, value, root);
}
},
pseudos: {
'first-child': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (Selector.handlers.previousElementSibling(node)) continue;
results.push(node);
}
return results;
},
'last-child': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (Selector.handlers.nextElementSibling(node)) continue;
results.push(node);
}
return results;
},
'only-child': function(nodes, value, root) {
var h = Selector.handlers;
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
results.push(node);
return results;
},
'nth-child':        function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root);
},
'nth-last-child':   function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, true);
},
'nth-of-type':      function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, false, true);
},
'nth-last-of-type': function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, formula, root, true, true);
},
'first-of-type':    function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, "1", root, false, true);
},
'last-of-type':     function(nodes, formula, root) {
return Selector.pseudos.nth(nodes, "1", root, true, true);
},
'only-of-type':     function(nodes, formula, root) {
var p = Selector.pseudos;
return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
},
getIndices: function(a, b, total) {
if (a == 0) return b > 0 ? [b] : [];
return $R(1, total).inject([], function(memo, i) {
if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
return memo;
});
},
nth: function(nodes, formula, root, reverse, ofType) {
if (nodes.length == 0) return [];
if (formula == 'even') formula = '2n+0';
if (formula == 'odd')  formula = '2n+1';
var h = Selector.handlers, results = [], indexed = [], m;
h.mark(nodes);
for (var i = 0, node; node = nodes[i]; i++) {
if (!node.parentNode._countedByPrototype) {
h.index(node.parentNode, reverse, ofType);
indexed.push(node.parentNode);
}
}
if (formula.match(/^\d+$/)) { // just a number
formula = Number(formula);
for (var i = 0, node; node = nodes[i]; i++)
if (node.nodeIndex == formula) results.push(node);
} else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
if (m[1] == "-") m[1] = -1;
var a = m[1] ? Number(m[1]) : 1;
var b = m[2] ? Number(m[2]) : 0;
var indices = Selector.pseudos.getIndices(a, b, nodes.length);
for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
for (var j = 0; j < l; j++)
if (node.nodeIndex == indices[j]) results.push(node);
}
}
h.unmark(nodes);
h.unmark(indexed);
return results;
},
'empty': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++) {
if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
results.push(node);
}
return results;
},
'not': function(nodes, selector, root) {
var h = Selector.handlers, selectorType, m;
var exclusions = new Selector(selector).findElements(root);
h.mark(exclusions);
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node._countedByPrototype) results.push(node);
h.unmark(exclusions);
return results;
},
'enabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (!node.disabled) results.push(node);
return results;
},
'disabled': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (node.disabled) results.push(node);
return results;
},
'checked': function(nodes, value, root) {
for (var i = 0, results = [], node; node = nodes[i]; i++)
if (node.checked) results.push(node);
return results;
}
},
operators: {
'=':  function(nv, v) { return nv == v; },
'!=': function(nv, v) { return nv != v; },
'^=': function(nv, v) { return nv.startsWith(v); },
'$=': function(nv, v) { return nv.endsWith(v); },
'*=': function(nv, v) { return nv.include(v); },
'~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
'|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
},
split: function(expression) {
var expressions = [];
expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
expressions.push(m[1].strip());
});
return expressions;
},
matchElements: function(elements, expression) {
var matches = $$(expression), h = Selector.handlers;
h.mark(matches);
for (var i = 0, results = [], element; element = elements[i]; i++)
if (element._countedByPrototype) results.push(element);
h.unmark(matches);
return results;
},
findElement: function(elements, expression, index) {
if (Object.isNumber(expression)) {
index = expression; expression = false;
}
return Selector.matchElements(elements, expression || '*')[index || 0];
},
findChildElements: function(element, expressions) {
expressions = Selector.split(expressions.join(','));
var results = [], h = Selector.handlers;
for (var i = 0, l = expressions.length, selector; i < l; i++) {
selector = new Selector(expressions[i].strip());
h.concat(results, selector.findElements(element));
}
return (l > 1) ? h.unique(results) : results;
}
});
if (Prototype.Browser.IE) {
Object.extend(Selector.handlers, {
concat: function(a, b) {
for (var i = 0, node; node = b[i]; i++)
if (node.tagName !== "!") a.push(node);
return a;
},
unmark: function(nodes) {
for (var i = 0, node; node = nodes[i]; i++)
node.removeAttribute('_countedByPrototype');
return nodes;
}
});
}
function $$() {
return Selector.findChildElements(document, $A(arguments));
}
var Form = {
reset: function(form) {
$(form).reset();
return form;
},
serializeElements: function(elements, options) {
if (typeof options != 'object') options = { hash: !!options };
else if (Object.isUndefined(options.hash)) options.hash = true;
var key, value, submitted = false, submit = options.submit;
var data = elements.inject({ }, function(result, element) {
if (!element.disabled && element.name) {
key = element.name; value = $(element).getValue();
if (value != null && (element.type != 'submit' || (!submitted &&
submit !== false && (!submit || key == submit) && (submitted = true)))) {
if (key in result) {
if (!Object.isArray(result[key])) result[key] = [result[key]];
result[key].push(value);
}
else result[key] = value;
}
}
return result;
});
return options.hash ? data : Object.toQueryString(data);
}
};
Form.Methods = {
serialize: function(form, options) {
return Form.serializeElements(Form.getElements(form), options);
},
getElements: function(form) {
return $A($(form).getElementsByTagName('*')).inject([],
function(elements, child) {
if (Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));
return elements;
}
);
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
if (!typeName && !name) return $A(inputs).map(Element.extend);
for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
var input = inputs[i];
if ((typeName && input.type != typeName) || (name && input.name != name))
continue;
matchingInputs.push(Element.extend(input));
}
return matchingInputs;
},
disable: function(form) {
form = $(form);
Form.getElements(form).invoke('disable');
return form;
},
enable: function(form) {
form = $(form);
Form.getElements(form).invoke('enable');
return form;
},
findFirstElement: function(form) {
var elements = $(form).getElements().findAll(function(element) {
return 'hidden' != element.type && !element.disabled;
});
var firstByIndex = elements.findAll(function(element) {
return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
}).sortBy(function(element) { return element.tabIndex }).first();
return firstByIndex ? firstByIndex : elements.find(function(element) {
return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
},
focusFirstElement: function(form) {
form = $(form);
form.findFirstElement().activate();
return form;
},
request: function(form, options) {
form = $(form), options = Object.clone(options || { });
var params = options.parameters, action = form.readAttribute('action') || '';
if (action.blank()) action = window.location.href;
options.parameters = form.serialize(true);
if (params) {
if (Object.isString(params)) params = params.toQueryParams();
Object.extend(options.parameters, params);
}
if (form.hasAttribute('method') && !options.method)
options.method = form.method;
return new Ajax.Request(action, options);
}
};
Form.Element = {
focus: function(element) {
$(element).focus();
return element;
},
select: function(element) {
$(element).select();
return element;
}
};
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
if (!element.disabled && element.name) {
var value = element.getValue();
if (value != undefined) {
var pair = { };
pair[element.name] = value;
return Object.toQueryString(pair);
}
}
return '';
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
return Form.Element.Serializers[method](element);
},
setValue: function(element, value) {
element = $(element);
var method = element.tagName.toLowerCase();
Form.Element.Serializers[method](element, value);
return element;
},
clear: function(element) {
$(element).value = '';
return element;
},
present: function(element) {
return $(element).value != '';
},
activate: function(element) {
element = $(element);
try {
element.focus();
if (element.select && (element.tagName.toLowerCase() != 'input' ||
!['button', 'reset', 'submit'].include(element.type)))
element.select();
} catch (e) { }
return element;
},
disable: function(element) {
element = $(element);
element.blur();
element.disabled = true;
return element;
},
enable: function(element) {
element = $(element);
element.disabled = false;
return element;
}
};
var Field = Form.Element;
var $F = Form.Element.Methods.getValue;
Form.Element.Serializers = {
input: function(element, value) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
return Form.Element.Serializers.inputSelector(element, value);
default:
return Form.Element.Serializers.textarea(element, value);
}
},
inputSelector: function(element, value) {
if (Object.isUndefined(value)) return element.checked ? element.value : null;
else element.checked = !!value;
},
textarea: function(element, value) {
if (Object.isUndefined(value)) return element.value;
else element.value = value;
},
select: function(element, index) {
if (Object.isUndefined(index))
return this[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
else {
var opt, value, single = !Object.isArray(index);
for (var i = 0, length = element.length; i < length; i++) {
opt = element.options[i];
value = this.optionValue(opt);
if (single) {
if (value == index) {
opt.selected = true;
return;
}
}
else opt.selected = index.include(value);
}
}
},
selectOne: function(element) {
var index = element.selectedIndex;
return index >= 0 ? this.optionValue(element.options[index]) : null;
},
selectMany: function(element) {
var values, length = element.length;
if (!length) return null;
for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
if (opt.selected) values.push(this.optionValue(opt));
}
return values;
},
optionValue: function(opt) {
return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
}
};
Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
initialize: function($super, element, frequency, callback) {
$super(callback, frequency);
this.element   = $(element);
this.lastValue = this.getValue();
},
execute: function() {
var value = this.getValue();
if (Object.isString(this.lastValue) && Object.isString(value) ?
this.lastValue != value : String(this.lastValue) != String(value)) {
this.callback(this.element, value);
this.lastValue = value;
}
}
});
Form.Element.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.Observer = Class.create(Abstract.TimedObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
Abstract.EventObserver = Class.create({
initialize: function(element, callback) {
this.element  = $(element);
this.callback = callback;
this.lastValue = this.getValue();
if (this.element.tagName.toLowerCase() == 'form')
this.registerFormCallbacks();
else
this.registerCallback(this.element);
},
onElementEvent: function() {
var value = this.getValue();
if (this.lastValue != value) {
this.callback(this.element, value);
this.lastValue = value;
}
},
registerFormCallbacks: function() {
Form.getElements(this.element).each(this.registerCallback, this);
},
registerCallback: function(element) {
if (element.type) {
switch (element.type.toLowerCase()) {
case 'checkbox':
case 'radio':
Event.observe(element, 'click', this.onElementEvent.bind(this));
break;
default:
Event.observe(element, 'change', this.onElementEvent.bind(this));
break;
}
}
}
});
Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.Element.getValue(this.element);
}
});
Form.EventObserver = Class.create(Abstract.EventObserver, {
getValue: function() {
return Form.serialize(this.element);
}
});
if (!window.Event) var Event = { };
Object.extend(Event, {
KEY_BACKSPACE: 8,
KEY_TAB:       9,
KEY_RETURN:   13,
KEY_ESC:      27,
KEY_LEFT:     37,
KEY_UP:       38,
KEY_RIGHT:    39,
KEY_DOWN:     40,
KEY_DELETE:   46,
KEY_HOME:     36,
KEY_END:      35,
KEY_PAGEUP:   33,
KEY_PAGEDOWN: 34,
KEY_INSERT:   45,
cache: { },
relatedTarget: function(event) {
var element;
switch(event.type) {
case 'mouseover': element = event.fromElement; break;
case 'mouseout':  element = event.toElement;   break;
default: return null;
}
return Element.extend(element);
}
});
Event.Methods = (function() {
var isButton;
if (Prototype.Browser.IE) {
var buttonMap = { 0: 1, 1: 4, 2: 2 };
isButton = function(event, code) {
return event.button == buttonMap[code];
};
} else if (Prototype.Browser.WebKit) {
isButton = function(event, code) {
switch (code) {
case 0: return event.which == 1 && !event.metaKey;
case 1: return event.which == 1 && event.metaKey;
default: return false;
}
};
} else {
isButton = function(event, code) {
return event.which ? (event.which === code + 1) : (event.button === code);
};
}
return {
isLeftClick:   function(event) { return isButton(event, 0) },
isMiddleClick: function(event) { return isButton(event, 1) },
isRightClick:  function(event) { return isButton(event, 2) },
element: function(event) {
var node = Event.extend(event).target;
return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
},
findElement: function(event, expression) {
var element = Event.element(event);
if (!expression) return element;
var elements = [element].concat(element.ancestors());
return Selector.findElement(elements, expression, 0);
},
pointer: function(event) {
return {
x: event.pageX || (event.clientX +
(document.documentElement.scrollLeft || document.body.scrollLeft)),
y: event.pageY || (event.clientY +
(document.documentElement.scrollTop || document.body.scrollTop))
};
},
pointerX: function(event) { return Event.pointer(event).x },
pointerY: function(event) { return Event.pointer(event).y },
stop: function(event) {
Event.extend(event);
event.preventDefault();
event.stopPropagation();
event.stopped = true;
}
};
})();
Event.extend = (function() {
var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
m[name] = Event.Methods[name].methodize();
return m;
});
if (Prototype.Browser.IE) {
Object.extend(methods, {
stopPropagation: function() { this.cancelBubble = true },
preventDefault:  function() { this.returnValue = false },
inspect: function() { return "[object Event]" }
});
return function(event) {
if (!event) return false;
if (event._extendedByPrototype) return event;
event._extendedByPrototype = Prototype.emptyFunction;
var pointer = Event.pointer(event);
Object.extend(event, {
target: event.srcElement,
relatedTarget: Event.relatedTarget(event),
pageX:  pointer.x,
pageY:  pointer.y
});
return Object.extend(event, methods);
};
} else {
Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
Object.extend(Event.prototype, methods);
return Prototype.K;
}
})();
Object.extend(Event, (function() {
var cache = Event.cache;
function getEventID(element) {
if (element._prototypeEventID) return element._prototypeEventID[0];
arguments.callee.id = arguments.callee.id || 1;
return element._prototypeEventID = [++arguments.callee.id];
}
function getDOMEventName(eventName) {
if (eventName && eventName.include(':')) return "dataavailable";
return eventName;
}
function getCacheForID(id) {
return cache[id] = cache[id] || { };
}
function getWrappersForEventName(id, eventName) {
var c = getCacheForID(id);
return c[eventName] = c[eventName] || [];
}
function createWrapper(element, eventName, handler) {
var id = getEventID(element);
var c = getWrappersForEventName(id, eventName);
if (c.pluck("handler").include(handler)) return false;
var wrapper = function(event) {
if (!Event || !Event.extend ||
(event.eventName && event.eventName != eventName))
return false;
Event.extend(event);
try{
if(handler != undefined)
{
handler.call(element, event);
}
}catch(e){}
};
wrapper.handler = handler;
c.push(wrapper);
return wrapper;
}
function findWrapper(id, eventName, handler) {
var c = getWrappersForEventName(id, eventName);
return c.find(function(wrapper) { return wrapper.handler == handler });
}
function destroyWrapper(id, eventName, handler) {
var c = getCacheForID(id);
if (!c[eventName]) return false;
c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
}
function destroyCache() {
for (var id in cache)
for (var eventName in cache[id])
cache[id][eventName] = null;
}
if (window.attachEvent) {
window.attachEvent("onunload", destroyCache);
}
return {
observe: function(element, eventName, handler) {
element = $(element);
var name = getDOMEventName(eventName);
var wrapper = createWrapper(element, eventName, handler);
if (!wrapper) return element;
if (element.addEventListener) {
element.addEventListener(name, wrapper, false);
} else {
element.attachEvent("on" + name, wrapper);
}
return element;
},
stopObserving: function(element, eventName, handler) {
element = $(element);
var id = getEventID(element), name = getDOMEventName(eventName);
if (!handler && eventName) {
getWrappersForEventName(id, eventName).each(function(wrapper) {
element.stopObserving(eventName, wrapper.handler);
});
return element;
} else if (!eventName) {
Object.keys(getCacheForID(id)).each(function(eventName) {
element.stopObserving(eventName);
});
return element;
}
var wrapper = findWrapper(id, eventName, handler);
if (!wrapper) return element;
if (element.removeEventListener) {
element.removeEventListener(name, wrapper, false);
} else {
element.detachEvent("on" + name, wrapper);
}
destroyWrapper(id, eventName, handler);
return element;
},
fire: function(element, eventName, memo) {
element = $(element);
if (element == document && document.createEvent && !element.dispatchEvent)
element = document.documentElement;
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent("dataavailable", true, true);
} else {
event = document.createEventObject();
event.eventType = "ondataavailable";
}
event.eventName = eventName;
event.memo = memo || { };
if (document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent(event.eventType, event);
}
return Event.extend(event);
}
};
})());
Object.extend(Event, Event.Methods);
Element.addMethods({
fire:          Event.fire,
observe:       Event.observe,
stopObserving: Event.stopObserving
});
Object.extend(document, {
fire:          Element.Methods.fire.methodize(),
observe:       Element.Methods.observe.methodize(),
stopObserving: Element.Methods.stopObserving.methodize(),
loaded:        false
});
(function() {
var timer;
function fireContentLoadedEvent() {
if (document.loaded) return;
if (timer) window.clearInterval(timer);
document.fire("dom:loaded");
document.loaded = true;
}
if (document.addEventListener) {
if (Prototype.Browser.WebKit) {
timer = window.setInterval(function() {
if (/loaded|complete/.test(document.readyState))
fireContentLoadedEvent();
}, 0);
Event.observe(window, "load", fireContentLoadedEvent);
} else {
document.addEventListener("DOMContentLoaded",
fireContentLoadedEvent, false);
}
} else {
document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
$("__onDOMContentLoaded").onreadystatechange = function() {
if (this.readyState == "complete") {
this.onreadystatechange = null;
fireContentLoadedEvent();
}
};
}
})();
Hash.toQueryString = Object.toQueryString;
var Toggle = { display: Element.toggle };
Element.Methods.childOf = Element.Methods.descendantOf;
var Insertion = {
Before: function(element, content) {
return Element.insert(element, {before:content});
},
Top: function(element, content) {
return Element.insert(element, {top:content});
},
Bottom: function(element, content) {
return Element.insert(element, {bottom:content});
},
After: function(element, content) {
return Element.insert(element, {after:content});
}
};
var $continue = new Error('"throw $continue" is deprecated, use "return" instead');
var Position = {
includeScrollOffsets: false,
prepare: function() {
this.deltaX =  window.pageXOffset
|| document.documentElement.scrollLeft
|| document.body.scrollLeft
|| 0;
this.deltaY =  window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop
|| 0;
},
within: function(element, x, y) {
if (this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element, x, y);
this.xcomp = x;
this.ycomp = y;
this.offset = Element.cumulativeOffset(element);
return (y >= this.offset[1] &&
y <  this.offset[1] + element.offsetHeight &&
x >= this.offset[0] &&
x <  this.offset[0] + element.offsetWidth);
},
withinIncludingScrolloffsets: function(element, x, y) {
var offsetcache = Element.cumulativeScrollOffset(element);
this.xcomp = x + offsetcache[0] - this.deltaX;
this.ycomp = y + offsetcache[1] - this.deltaY;
this.offset = Element.cumulativeOffset(element);
return (this.ycomp >= this.offset[1] &&
this.ycomp <  this.offset[1] + element.offsetHeight &&
this.xcomp >= this.offset[0] &&
this.xcomp <  this.offset[0] + element.offsetWidth);
},
overlap: function(mode, element) {
if (!mode) return 0;
if (mode == 'vertical')
return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
element.offsetHeight;
if (mode == 'horizontal')
return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
element.offsetWidth;
},
cumulativeOffset: Element.Methods.cumulativeOffset,
positionedOffset: Element.Methods.positionedOffset,
absolutize: function(element) {
Position.prepare();
return Element.absolutize(element);
},
relativize: function(element) {
Position.prepare();
return Element.relativize(element);
},
realOffset: Element.Methods.cumulativeScrollOffset,
offsetParent: Element.Methods.getOffsetParent,
page: Element.Methods.viewportOffset,
clone: function(source, target, options) {
options = options || { };
return Element.clonePosition(target, source, options);
}
};
if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
function iter(name) {
return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
}
instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
function(element, className) {
className = className.toString().strip();
var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
} : function(element, className) {
className = className.toString().strip();
var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
if (!classNames && !className) return elements;
var nodes = $(element).getElementsByTagName('*');
className = ' ' + className + ' ';
for (var i = 0, child, cn; child = nodes[i]; i++) {
if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
(classNames && classNames.all(function(name) {
return !name.toString().blank() && cn.include(' ' + name + ' ');
}))))
elements.push(Element.extend(child));
}
return elements;
};
return function(className, parentElement) {
return $(parentElement || document.body).getElementsByClassName(className);
};
}(Element.Methods);
Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
initialize: function(element) {
this.element = $(element);
},
_each: function(iterator) {
this.element.className.split(/\s+/).select(function(name) {
return name.length > 0;
})._each(iterator);
},
set: function(className) {
this.element.className = className;
},
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
this.set($A(this).concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
this.set($A(this).without(classNameToRemove).join(' '));
},
toString: function() {
return $A(this).join(' ');
}
};
Object.extend(Element.ClassNames.prototype, Enumerable);
Element.addMethods();
var Scriptaculous = {
Version: '1.8.1',
require: function(libraryName) {
document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
},
REQUIRED_PROTOTYPE: '1.6.0',
load: function() {
function convertVersionString(versionString){
var r = versionString.split('.');
return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
}
if((typeof Prototype=='undefined') || 
(typeof Element == 'undefined') || 
(typeof Element.Methods=='undefined') ||
(convertVersionString(Prototype.Version) < 
convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
throw("script.aculo.us requires the Prototype JavaScript framework >= " +
Scriptaculous.REQUIRED_PROTOTYPE);
$A(document.getElementsByTagName("script")).findAll( function(s) {
return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
}).each( function(s) {
var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
var includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
}
}
Scriptaculous.load();
String.prototype.parseColor = function() {  
var color = '#';
if (this.slice(0,4) == 'rgb(') {  
var cols = this.slice(4,this.length-1).split(',');  
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
} else {  
if (this.slice(0,1) == '#') {  
if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
if (this.length==7) color = this.toLowerCase();  
}  
}  
return (color.length==7 ? color : (arguments[0] || this));  
};
Element.collectTextNodes = function(element) {  
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue : 
(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
}).flatten().join('');
};
Element.collectTextNodesIgnoreClass = function(element, className) {  
return $A($(element).childNodes).collect( function(node) {
return (node.nodeType==3 ? node.nodeValue : 
((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
Element.collectTextNodesIgnoreClass(node, className) : ''));
}).flatten().join('');
};
Element.setContentZoom = function(element, percent) {
element = $(element);  
element.setStyle({fontSize: (percent/100) + 'em'});   
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
return element;
};
Element.getInlineOpacity = function(element){
return $(element).style.opacity || '';
};
Element.forceRerendering = function(element) {
try {
element = $(element);
var n = document.createTextNode(' ');
element.appendChild(n);
element.removeChild(n);
} catch(e) { }
};
var Effect = {
_elementDoesNotExistError: {
name: 'ElementDoesNotExistError',
message: 'The specified DOM element does not exist, but is required for this effect to operate'
},
Transitions: {
linear: Prototype.K,
sinoidal: function(pos) {
return (-Math.cos(pos*Math.PI)/2) + 0.5;
},
reverse: function(pos) {
return 1-pos;
},
flicker: function(pos) {
var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
return pos > 1 ? 1 : pos;
},
wobble: function(pos) {
return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
},
pulse: function(pos, pulses) { 
pulses = pulses || 5; 
return (
((pos % (1/pulses)) * pulses).round() == 0 ? 
((pos * pulses * 2) - (pos * pulses * 2).floor()) : 
1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
);
},
spring: function(pos) { 
return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); 
},
none: function(pos) {
return 0;
},
full: function(pos) {
return 1;
}
},
DefaultOptions: {
duration:   1.0,   // seconds
fps:        100,   // 100= assume 66fps max.
sync:       false, // true for combining
from:       0.0,
to:         1.0,
delay:      0.0,
queue:      'parallel'
},
tagifyText: function(element) {
var tagifyStyle = 'position:relative';
if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
element = $(element);
$A(element.childNodes).each( function(child) {
if (child.nodeType==3) {
child.nodeValue.toArray().each( function(character) {
element.insertBefore(
new Element('span', {style: tagifyStyle}).update(
character == ' ' ? String.fromCharCode(160) : character), 
child);
});
Element.remove(child);
}
});
},
multiple: function(element, effect) {
var elements;
if (((typeof element == 'object') || 
Object.isFunction(element)) && 
(element.length))
elements = element;
else
elements = $(element).childNodes;
var options = Object.extend({
speed: 0.1,
delay: 0.0
}, arguments[2] || { });
var masterDelay = options.delay;
$A(elements).each( function(element, index) {
new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
});
},
PAIRS: {
'slide':  ['SlideDown','SlideUp'],
'blind':  ['BlindDown','BlindUp'],
'appear': ['Appear','Fade']
},
toggle: function(element, effect) {
element = $(element);
effect = (effect || 'appear').toLowerCase();
var options = Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
}, arguments[2] || { });
Effect[element.visible() ? 
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
}
};
Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
Effect.ScopedQueue = Class.create(Enumerable, {
initialize: function() {
this.effects  = [];
this.interval = null;    
},
_each: function(iterator) {
this.effects._each(iterator);
},
add: function(effect) {
var timestamp = new Date().getTime();
var position = Object.isString(effect.options.queue) ? 
effect.options.queue : effect.options.queue.position;
switch(position) {
case 'front':
this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
e.startOn  += effect.finishOn;
e.finishOn += effect.finishOn;
});
break;
case 'with-last':
timestamp = this.effects.pluck('startOn').max() || timestamp;
break;
case 'end':
timestamp = this.effects.pluck('finishOn').max() || timestamp;
break;
}
effect.startOn  += timestamp;
effect.finishOn += timestamp;
if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
this.effects.push(effect);
if (!this.interval)
this.interval = setInterval(this.loop.bind(this), 15);
},
remove: function(effect) {
this.effects = this.effects.reject(function(e) { return e==effect });
if (this.effects.length == 0) {
clearInterval(this.interval);
this.interval = null;
}
},
loop: function() {
var timePos = new Date().getTime();
for(var i=0, len=this.effects.length;i<len;i++) 
this.effects[i] && this.effects[i].loop(timePos);
}
});
Effect.Queues = {
instances: $H(),
get: function(queueName) {
if (!Object.isString(queueName)) return queueName;
return this.instances.get(queueName) ||
this.instances.set(queueName, new Effect.ScopedQueue());
}
};
Effect.Queue = Effect.Queues.get('global');
Effect.Base = Class.create({
position: null,
start: function(options) {
function codeForEvent(options,eventName){
return (
(options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
(options[eventName] ? 'this.options.'+eventName+'(this);' : '')
);
}
if (options && options.transition === false) options.transition = Effect.Transitions.linear;
this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
this.currentFrame = 0;
this.state        = 'idle';
this.startOn      = this.options.delay*1000;
this.finishOn     = this.startOn+(this.options.duration*1000);
this.fromToDelta  = this.options.to-this.options.from;
this.totalTime    = this.finishOn-this.startOn;
this.totalFrames  = this.options.fps*this.options.duration;
eval('this.render = function(pos){ '+
'if (this.state=="idle"){this.state="running";'+
codeForEvent(this.options,'beforeSetup')+
(this.setup ? 'this.setup();':'')+ 
codeForEvent(this.options,'afterSetup')+
'};if (this.state=="running"){'+
'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
'this.position=pos;'+
codeForEvent(this.options,'beforeUpdate')+
(this.update ? 'this.update(pos);':'')+
codeForEvent(this.options,'afterUpdate')+
'}}');
this.event('beforeStart');
if (!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue) ? 
'global' : this.options.queue.scope).add(this);
},
loop: function(timePos) {
if (timePos >= this.startOn) {
if (timePos >= this.finishOn) {
this.render(1.0);
this.cancel();
this.event('beforeFinish');
if (this.finish) this.finish(); 
this.event('afterFinish');
return;  
}
var pos   = (timePos - this.startOn) / this.totalTime,
frame = (pos * this.totalFrames).round();
if (frame > this.currentFrame) {
this.render(pos);
this.currentFrame = frame;
}
}
},
cancel: function() {
if (!this.options.sync)
Effect.Queues.get(Object.isString(this.options.queue) ? 
'global' : this.options.queue.scope).remove(this);
this.state = 'finished';
},
event: function(eventName) {
if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
if (this.options[eventName]) this.options[eventName](this);
},
inspect: function() {
var data = $H();
for(property in this)
if (!Object.isFunction(this[property])) data.set(property, this[property]);
return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
}
});
Effect.Parallel = Class.create(Effect.Base, {
initialize: function(effects) {
this.effects = effects || [];
this.start(arguments[1]);
},
update: function(position) {
this.effects.invoke('render', position);
},
finish: function(position) {
this.effects.each( function(effect) {
effect.render(1.0);
effect.cancel();
effect.event('beforeFinish');
if (effect.finish) effect.finish(position);
effect.event('afterFinish');
});
}
});
Effect.Tween = Class.create(Effect.Base, {
initialize: function(object, from, to) {
object = Object.isString(object) ? $(object) : object;
var args = $A(arguments), method = args.last(), 
options = args.length == 5 ? args[3] : null;
this.method = Object.isFunction(method) ? method.bind(object) :
Object.isFunction(object[method]) ? object[method].bind(object) : 
function(value) { object[method] = value };
this.start(Object.extend({ from: from, to: to }, options || { }));
},
update: function(position) {
this.method(position);
}
});
Effect.Event = Class.create(Effect.Base, {
initialize: function() {
this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
},
update: Prototype.emptyFunction
});
Effect.Opacity = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
var options = Object.extend({
from: this.element.getOpacity() || 0.0,
to:   1.0
}, arguments[1] || { });
this.start(options);
},
update: function(position) {
this.element.setOpacity(position);
}
});
Effect.Move = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
x:    0,
y:    0,
mode: 'relative'
}, arguments[1] || { });
this.start(options);
},
setup: function() {
this.element.makePositioned();
this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
if (this.options.mode == 'absolute') {
this.options.x = this.options.x - this.originalLeft;
this.options.y = this.options.y - this.originalTop;
}
},
update: function(position) {
this.element.setStyle({
left: (this.options.x  * position + this.originalLeft).round() + 'px',
top:  (this.options.y  * position + this.originalTop).round()  + 'px'
});
}
});
Effect.MoveBy = function(element, toTop, toLeft) {
return new Effect.Move(element, 
Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};
Effect.Scale = Class.create(Effect.Base, {
initialize: function(element, percent) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
scaleX: true,
scaleY: true,
scaleContent: true,
scaleFromCenter: false,
scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
scaleFrom: 100.0,
scaleTo:   percent
}, arguments[2] || { });
this.start(options);
},
setup: function() {
this.restoreAfterFinish = this.options.restoreAfterFinish || false;
this.elementPositioning = this.element.getStyle('position');
this.originalStyle = { };
['top','left','width','height','fontSize'].each( function(k) {
this.originalStyle[k] = this.element.style[k];
}.bind(this));
this.originalTop  = this.element.offsetTop;
this.originalLeft = this.element.offsetLeft;
var fontSize = this.element.getStyle('font-size') || '100%';
['em','px','%','pt'].each( function(fontSizeType) {
if (fontSize.indexOf(fontSizeType)>0) {
this.fontSize     = parseFloat(fontSize);
this.fontSizeType = fontSizeType;
}
}.bind(this));
this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
this.dims = null;
if (this.options.scaleMode=='box')
this.dims = [this.element.offsetHeight, this.element.offsetWidth];
if (/^content/.test(this.options.scaleMode))
this.dims = [this.element.scrollHeight, this.element.scrollWidth];
if (!this.dims)
this.dims = [this.options.scaleMode.originalHeight,
this.options.scaleMode.originalWidth];
},
update: function(position) {
var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
if (this.options.scaleContent && this.fontSize)
this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
},
finish: function(position) {
if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
},
setDimensions: function(height, width) {
var d = { };
if (this.options.scaleX) d.width = width.round() + 'px';
if (this.options.scaleY) d.height = height.round() + 'px';
if (this.options.scaleFromCenter) {
var topd  = (height - this.dims[0])/2;
var leftd = (width  - this.dims[1])/2;
if (this.elementPositioning == 'absolute') {
if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
} else {
if (this.options.scaleY) d.top = -topd + 'px';
if (this.options.scaleX) d.left = -leftd + 'px';
}
}
this.element.setStyle(d);
}
});
Effect.Highlight = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
this.start(options);
},
setup: function() {
if (this.element.getStyle('display')=='none') { this.cancel(); return; }
this.oldStyle = { };
if (!this.options.keepBackgroundImage) {
this.oldStyle.backgroundImage = this.element.getStyle('background-image');
this.element.setStyle({backgroundImage: 'none'});
}
if (!this.options.endcolor)
this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
if (!this.options.restorecolor)
this.options.restorecolor = this.element.getStyle('background-color');
this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
},
update: function(position) {
this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
},
finish: function() {
this.element.setStyle(Object.extend(this.oldStyle, {
backgroundColor: this.options.restorecolor
}));
}
});
Effect.ScrollTo = function(element) {
var options = arguments[1] || { },
scrollOffsets = document.viewport.getScrollOffsets(),
elementOffsets = $(element).cumulativeOffset(),
max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();  
if (options.offset) elementOffsets[1] += options.offset;
return new Effect.Tween(null,
scrollOffsets.top,
elementOffsets[1] > max ? max : elementOffsets[1],
options,
function(p){ scrollTo(scrollOffsets.left, p.round()) }
);
};
Effect.Fade = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
var options = Object.extend({
from: element.getOpacity() || 1.0,
to:   0.0,
afterFinishInternal: function(effect) { 
if (effect.options.to!=0) return;
effect.element.hide().setStyle({opacity: oldOpacity}); 
}
}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
to:   1.0,
afterFinishInternal: function(effect) {
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from).show(); 
}}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
Effect.Puff = function(element) {
element = $(element);
var oldStyle = { 
opacity: element.getInlineOpacity(), 
position: element.getStyle('position'),
top:  element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height
};
return new Effect.Parallel(
[ new Effect.Scale(element, 200, 
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
Object.extend({ duration: 1.0, 
beforeSetupInternal: function(effect) {
Position.absolutize(effect.effects[0].element)
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().setStyle(oldStyle); }
}, arguments[1] || { })
);
};
Effect.BlindUp = function(element) {
element = $(element);
element.makeClipping();
return new Effect.Scale(element, 0,
Object.extend({ scaleContent: false, 
scaleX: false, 
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping();
} 
}, arguments[1] || { })
);
};
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({ 
scaleContent: false, 
scaleX: false,
scaleFrom: 0,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makeClipping().setStyle({height: '0px'}).show(); 
},  
afterFinishInternal: function(effect) {
effect.element.undoClipping();
}
}, arguments[1] || { }));
};
Effect.SwitchOff = function(element) {
element = $(element);
var oldOpacity = element.getInlineOpacity();
return new Effect.Appear(element, Object.extend({
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
new Effect.Scale(effect.element, 1, { 
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) { 
effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
}
}, arguments[1] || { }));
};
Effect.DropOut = function(element) {
element = $(element);
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left'),
opacity: element.getInlineOpacity() };
return new Effect.Parallel(
[ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
Object.extend(
{ duration: 0.5,
beforeSetup: function(effect) {
effect.effects[0].element.makePositioned(); 
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
} 
}, arguments[1] || { }));
};
Effect.Shake = function(element) {
element = $(element);
var options = Object.extend({
distance: 20,
duration: 0.5
}, arguments[1] || {});
var distance = parseFloat(options.distance);
var split = parseFloat(options.duration) / 10.0;
var oldStyle = {
top: element.getStyle('top'),
left: element.getStyle('left') };
return new Effect.Move(element,
{ x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
effect.element.undoPositioned().setStyle(oldStyle);
}}) }}) }}) }}) }}) }});
};
Effect.SlideDown = function(element) {
element = $(element).cleanWhitespace();
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({ 
scaleContent: false, 
scaleX: false, 
scaleFrom: window.opera ? 0 : 1,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if (window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().setStyle({height: '0px'}).show(); 
},
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' }); 
},
afterFinishInternal: function(effect) {
effect.element.undoClipping().undoPositioned();
effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || { })
);
};
Effect.SlideUp = function(element) {
element = $(element).cleanWhitespace();
var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, window.opera ? 0 : 1,
Object.extend({ scaleContent: false, 
scaleX: false, 
scaleMode: 'box',
scaleFrom: 100,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
effect.element.down().makePositioned();
if (window.opera) effect.element.setStyle({top: ''});
effect.element.makeClipping().show();
},  
afterUpdateInternal: function(effect) {
effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned();
effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
}
}, arguments[1] || { })
);
};
Effect.Squish = function(element) {
return new Effect.Scale(element, window.opera ? 1 : 0, { 
restoreAfterFinish: true,
beforeSetup: function(effect) {
effect.element.makeClipping(); 
},  
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping(); 
}
});
};
Effect.Grow = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.full
}, arguments[1] || { });
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();    
var initialMoveX, initialMoveY;
var moveX, moveY;
switch (options.direction) {
case 'top-left':
initialMoveX = initialMoveY = moveX = moveY = 0; 
break;
case 'top-right':
initialMoveX = dims.width;
initialMoveY = moveY = 0;
moveX = -dims.width;
break;
case 'bottom-left':
initialMoveX = moveX = 0;
initialMoveY = dims.height;
moveY = -dims.height;
break;
case 'bottom-right':
initialMoveX = dims.width;
initialMoveY = dims.height;
moveX = -dims.width;
moveY = -dims.height;
break;
case 'center':
initialMoveX = dims.width / 2;
initialMoveY = dims.height / 2;
moveX = -dims.width / 2;
moveY = -dims.height / 2;
break;
}
return new Effect.Move(element, {
x: initialMoveX,
y: initialMoveY,
duration: 0.01, 
beforeSetup: function(effect) {
effect.element.hide().makeClipping().makePositioned();
},
afterFinishInternal: function(effect) {
new Effect.Parallel(
[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
new Effect.Scale(effect.element, 100, {
scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
effect.effects[0].element.setStyle({height: '0px'}).show(); 
},
afterFinishInternal: function(effect) {
effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
}
}, options)
)
}
});
};
Effect.Shrink = function(element) {
element = $(element);
var options = Object.extend({
direction: 'center',
moveTransition: Effect.Transitions.sinoidal,
scaleTransition: Effect.Transitions.sinoidal,
opacityTransition: Effect.Transitions.none
}, arguments[1] || { });
var oldStyle = {
top: element.style.top,
left: element.style.left,
height: element.style.height,
width: element.style.width,
opacity: element.getInlineOpacity() };
var dims = element.getDimensions();
var moveX, moveY;
switch (options.direction) {
case 'top-left':
moveX = moveY = 0;
break;
case 'top-right':
moveX = dims.width;
moveY = 0;
break;
case 'bottom-left':
moveX = 0;
moveY = dims.height;
break;
case 'bottom-right':
moveX = dims.width;
moveY = dims.height;
break;
case 'center':  
moveX = dims.width / 2;
moveY = dims.height / 2;
break;
}
return new Effect.Parallel(
[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
], Object.extend({            
beforeStartInternal: function(effect) {
effect.effects[0].element.makePositioned().makeClipping(); 
},
afterFinishInternal: function(effect) {
effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
}, options)
);
};
Effect.Pulsate = function(element) {
element = $(element);
var options    = arguments[1] || { };
var oldOpacity = element.getInlineOpacity();
var transition = options.transition || Effect.Transitions.sinoidal;
var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
reverser.bind(transition);
return new Effect.Opacity(element, 
Object.extend(Object.extend({  duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
};
Effect.Fold = function(element) {
element = $(element);
var oldStyle = {
top: element.style.top,
left: element.style.left,
width: element.style.width,
height: element.style.height };
element.makeClipping();
return new Effect.Scale(element, 5, Object.extend({   
scaleContent: false,
scaleX: false,
afterFinishInternal: function(effect) {
new Effect.Scale(element, 1, { 
scaleContent: false, 
scaleY: false,
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().setStyle(oldStyle);
} });
}}, arguments[1] || { }));
};
Effect.Morph = Class.create(Effect.Base, {
initialize: function(element) {
this.element = $(element);
if (!this.element) throw(Effect._elementDoesNotExistError);
var options = Object.extend({
style: { }
}, arguments[1] || { });
if (!Object.isString(options.style)) this.style = $H(options.style);
else {
if (options.style.include(':'))
this.style = options.style.parseStyle();
else {
this.element.addClassName(options.style);
this.style = $H(this.element.getStyles());
this.element.removeClassName(options.style);
var css = this.element.getStyles();
this.style = this.style.reject(function(style) {
return style.value == css[style.key];
});
options.afterFinishInternal = function(effect) {
effect.element.addClassName(effect.options.style);
effect.transforms.each(function(transform) {
effect.element.style[transform.style] = '';
});
}
}
}
this.start(options);
},
setup: function(){
function parseColor(color){
if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
color = color.parseColor();
return $R(0,2).map(function(i){
return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
});
}
this.transforms = this.style.map(function(pair){
var property = pair[0], value = pair[1], unit = null;
if (value.parseColor('#zzzzzz') != '#zzzzzz') {
value = value.parseColor();
unit  = 'color';
} else if (property == 'opacity') {
value = parseFloat(value);
if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom: 1});
} else if (Element.CSS_LENGTH.test(value)) {
var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
value = parseFloat(components[1]);
unit = (components.length == 3) ? components[2] : null;
}
var originalValue = this.element.getStyle(property);
return { 
style: property.camelize(), 
originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
targetValue: unit=='color' ? parseColor(value) : value,
unit: unit
};
}.bind(this)).reject(function(transform){
return (
(transform.originalValue == transform.targetValue) ||
(
transform.unit != 'color' &&
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
)
)
});
},
update: function(position) {
var style = { }, transform, i = this.transforms.length;
while(i--)
style[(transform = this.transforms[i]).style] = 
transform.unit=='color' ? '#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
(transform.originalValue +
(transform.targetValue - transform.originalValue) * position).toFixed(3) + 
(transform.unit === null ? '' : transform.unit);
this.element.setStyle(style, true);
}
});
Effect.Transform = Class.create({
initialize: function(tracks){
this.tracks  = [];
this.options = arguments[1] || { };
this.addTracks(tracks);
},
addTracks: function(tracks){
tracks.each(function(track){
track = $H(track);
var data = track.values().first();
this.tracks.push($H({
ids:     track.keys().first(),
effect:  Effect.Morph,
options: { style: data }
}));
}.bind(this));
return this;
},
play: function(){
return new Effect.Parallel(
this.tracks.map(function(track){
var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
var elements = [$(ids) || $$(ids)].flatten();
return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
}).flatten(),
this.options
);
}
});
Element.CSS_PROPERTIES = $w(
'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
'fontSize fontWeight height left letterSpacing lineHeight ' +
'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
'right textIndent top width wordSpacing zIndex');
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
var style, styleRules = $H();
if (Prototype.Browser.WebKit)
style = new Element('div',{style:this}).style;
else {
String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
style = String.__parseStyleElement.childNodes[0].style;
}
Element.CSS_PROPERTIES.each(function(property){
if (style[property]) styleRules.set(property, style[property]); 
});
if (Prototype.Browser.IE && this.include('opacity'))
styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
return styleRules;
};
if (document.defaultView && document.defaultView.getComputedStyle) {
Element.getStyles = function(element) {
var css = document.defaultView.getComputedStyle($(element), null);
return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
styles[property] = css[property];
return styles;
});
};
} else {
Element.getStyles = function(element) {
element = $(element);
var css = element.currentStyle, styles;
styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
results[property] = css[property];
return results;
});
if (!styles.opacity) styles.opacity = element.getOpacity();
return styles;
};
};
Effect.Methods = {
morph: function(element, style) {
element = $(element);
new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
return element;
},
visualEffect: function(element, effect, options) {
element = $(element)
var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
new Effect[klass](element, options);
return element;
},
highlight: function(element, options) {
element = $(element);
new Effect.Highlight(element, options);
return element;
}
};
$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
'pulsate shake puff squish switchOff dropOut').each(
function(effect) { 
Effect.Methods[effect] = function(element, options){
element = $(element);
Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
return element;
}
}
);
$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( 
function(f) { Effect.Methods[f] = Element[f]; }
);
Element.addMethods(Effect.Methods);
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { }
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element          = $(element)
this.element     = element; 
this.update      = $(update);  
this.hasFocus    = false; 
this.changed     = false; 
this.active      = false; 
this.index       = 0;     
this.entryCount  = 0;
this.oldElementValue = this.element.value;
if(this.setOptions)
this.setOptions(options);
else
this.options = options || { };
this.options.paramName    = this.options.paramName || this.element.name;
this.options.tokens       = this.options.tokens || [];
this.options.frequency    = this.options.frequency || 0.4;
this.options.minChars     = this.options.minChars || 1;
this.options.onShow       = this.options.onShow || 
function(element, update){ 
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false, 
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide || 
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if(typeof(this.options.tokens) == 'string') 
this.options.tokens = new Array(this.options.tokens);
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix && 
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update, 
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
Event.stop(event);
return;
}
else 
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer = 
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex) 
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;     
}, 
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ? 
Element.addClassName(this.getEntry(i),"selected") : 
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) { 
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = $(selectedElement).select('.' + this.options.select) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
} else {
this.element.value = value;
}
this.oldElementValue = this.element.value;
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount = 
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else { 
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
} else {
this.render();
}
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;   
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
this.oldElementValue = this.element.value;
},
getToken: function() {
var bounds = this.getTokenBounds();
return this.element.value.substring(bounds[0], bounds[1]).strip();
},
getTokenBounds: function() {
if (null != this.tokenBounds) return this.tokenBounds;
var value = this.element.value;
if (value.strip().empty()) return [-1, 0];
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
var offset = (diff == this.oldElementValue.length ? 1 : 0);
var prevTokenPos = -1, nextTokenPos = value.length;
var tp;
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
if (tp > prevTokenPos) prevTokenPos = tp;
tp = value.indexOf(this.options.tokens[index], diff + offset);
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
}
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
}
});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
var boundary = Math.min(newS.length, oldS.length);
for (var index = 0; index < boundary; ++index)
if (newS[index] != oldS[index])
return index;
return boundary;
};
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous  = true;
this.options.onComplete    = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url                   = url;
},
getUpdatedChoices: function() {
this.startIndicator();
var entry = encodeURIComponent(this.options.paramName) + '=' + 
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams) 
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
Autocompleter.Local = Class.create(Autocompleter.Base, {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret       = []; // Beginning matches
var partial   = []; // Inside matches
var entry     = instance.getToken();
var count     = 0;
for (var i = 0; i < instance.options.array.length &&  
ret.length < instance.options.choices ; i++) { 
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ? 
elem.toLowerCase().indexOf(entry.toLowerCase()) : 
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) { 
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + 
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars && 
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ? 
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
}
});
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
}
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
this.url = url;
this.element = element = $(element);
this.prepareOptions();
this._controls = { };
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
Object.extend(this.options, options || { });
if (!this.options.formId && this.element.id) {
this.options.formId = this.element.id + '-inplaceeditor';
if ($(this.options.formId))
this.options.formId = '';
}
if (this.options.externalControl)
this.options.externalControl = $(this.options.externalControl);
if (!this.options.externalControl)
this.options.externalControlOnly = false;
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
this.element.title = this.options.clickToEditText;
this._boundCancelHandler = this.handleFormCancellation.bind(this);
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
this._boundWrapperHandler = this.wrapUp.bind(this);
this.registerListeners();
},
checkForEscapeOrReturn: function(e) {
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
if (Event.KEY_ESC == e.keyCode)
this.handleFormCancellation(e);
else if (Event.KEY_RETURN == e.keyCode)
this.handleFormSubmission(e);
},
createControl: function(mode, handler, extraClasses) {
var control = this.options[mode + 'Control'];
var text = this.options[mode + 'Text'];
if ('button' == control) {
var btn = document.createElement('input');
btn.type = 'submit';
btn.value = text;
btn.className = 'editor_' + mode + '_button';
if ('cancel' == mode)
btn.onclick = this._boundCancelHandler;
this._form.appendChild(btn);
this._controls[mode] = btn;
} else if ('link' == control) {
var link = document.createElement('a');
link.href = '#';
link.appendChild(document.createTextNode(text));
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
link.className = 'editor_' + mode + '_link';
if (extraClasses)
link.className += ' ' + extraClasses;
this._form.appendChild(link);
this._controls[mode] = link;
}
},
createEditField: function() {
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
var fld;
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
fld = document.createElement('input');
fld.type = 'text';
var size = this.options.size || this.options.cols || 0;
if (0 < size) fld.size = size;
} else {
fld = document.createElement('textarea');
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
fld.cols = this.options.cols || 40;
}
fld.name = this.options.paramName;
fld.value = text; // No HTML breaks conversion anymore
fld.className = 'editor_field';
if (this.options.submitOnBlur)
fld.onblur = this._boundSubmitHandler;
this._controls.editor = fld;
if (this.options.loadTextURL)
this.loadExternalText();
this._form.appendChild(this._controls.editor);
},
createForm: function() {
var ipe = this;
function addText(mode, condition) {
var text = ipe.options['text' + mode + 'Controls'];
if (!text || condition === false) return;
ipe._form.appendChild(document.createTextNode(text));
};
this._form = $(document.createElement('form'));
this._form.id = this.options.formId;
this._form.addClassName(this.options.formClassName);
this._form.onsubmit = this._boundSubmitHandler;
this.createEditField();
if ('textarea' == this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));
if (this.options.onFormCustomization)
this.options.onFormCustomization(this, this._form);
addText('Before', this.options.okControl || this.options.cancelControl);
this.createControl('ok', this._boundSubmitHandler);
addText('Between', this.options.okControl && this.options.cancelControl);
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
addText('After', this.options.okControl || this.options.cancelControl);
},
destroy: function() {
if (this._oldInnerHTML)
this.element.innerHTML = this._oldInnerHTML;
this.leaveEditMode();
this.unregisterListeners();
},
enterEditMode: function(e) {
if (this._saving || this._editing) return;
this._editing = true;
this.triggerCallback('onEnterEditMode');
if (this.options.externalControl)
this.options.externalControl.hide();
this.element.hide();
this.createForm();
this.element.parentNode.insertBefore(this._form, this.element);
if (!this.options.loadTextURL)
this.postProcessEditField();
if (e) Event.stop(e);
},
enterHover: function(e) {
if (this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML;
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
if (this._oldInnerHTML) {
this.element.innerHTML = this._oldInnerHTML;
this._oldInnerHTML = null;
}
},
handleFormCancellation: function(e) {
this.wrapUp();
if (e) Event.stop(e);
},
handleFormSubmission: function(e) {
var form = this._form;
var value = $F(this._controls.editor);
this.prepareSubmission();
var params = this.options.callback(form, value) || '';
if (Object.isString(params))
params = params.toQueryParams();
params.editorId = this.element.id;
if (this.options.htmlResponse) {
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Updater({ success: this.element }, this.url, options);
} else {
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.url, options);
}
if (e) Event.stop(e);
},
leaveEditMode: function() {
this.element.removeClassName(this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
if (this.options.externalControl)
this.options.externalControl.show();
this._saving = false;
this._editing = false;
this._oldInnerHTML = null;
this.triggerCallback('onLeaveEditMode');
},
leaveHover: function(e) {
if (this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onLeaveHover');
},
loadExternalText: function() {
this._form.addClassName(this.options.loadingClassName);
this._controls.editor.disabled = true;
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._form.removeClassName(this.options.loadingClassName);
var text = transport.responseText;
if (this.options.stripLoadedTextTags)
text = text.stripTags();
this._controls.editor.value = text;
this._controls.editor.disabled = false;
this.postProcessEditField();
}.bind(this),
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.options.loadTextURL, options);
},
postProcessEditField: function() {
var fpc = this.options.fieldPostCreation;
if (fpc)
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
},
prepareOptions: function() {
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
Object.extend(this.options, defs);
}.bind(this));
},
prepareSubmission: function() {
this._saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
registerListeners: function() {
this._listeners = { };
var listener;
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
listener = this[pair.value].bind(this);
this._listeners[pair.key] = listener;
if (!this.options.externalControlOnly)
this.element.observe(pair.key, listener);
if (this.options.externalControl)
this.options.externalControl.observe(pair.key, listener);
}.bind(this));
},
removeForm: function() {
if (!this._form) return;
this._form.remove();
this._form = null;
this._controls = { };
},
showSaving: function() {
this._oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
this.element.addClassName(this.options.savingClassName);
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
},
triggerCallback: function(cbName, arg) {
if ('function' == typeof this.options[cbName]) {
this.options[cbName](this, arg);
}
},
unregisterListeners: function() {
$H(this._listeners).each(function(pair) {
if (!this.options.externalControlOnly)
this.element.stopObserving(pair.key, pair.value);
if (this.options.externalControl)
this.options.externalControl.stopObserving(pair.key, pair.value);
}.bind(this));
},
wrapUp: function(transport) {
this.leaveEditMode();
this._boundComplete(transport, this.element);
}
});
Object.extend(Ajax.InPlaceEditor.prototype, {
dispose: Ajax.InPlaceEditor.prototype.destroy
});
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
initialize: function($super, element, url, options) {
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
$super(element, url, options);
},
createEditField: function() {
var list = document.createElement('select');
list.name = this.options.paramName;
list.size = 1;
this._controls.editor = list;
this._collection = this.options.collection || [];
if (this.options.loadCollectionURL)
this.loadCollection();
else
this.checkForExternalText();
this._form.appendChild(this._controls.editor);
},
loadCollection: function() {
this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw 'Server returned an invalid collection representation.';
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadCollectionURL, options);
},
showLoadingText: function(text) {
this._controls.editor.disabled = true;
var tempOption = this._controls.editor.firstChild;
if (!tempOption) {
tempOption = document.createElement('option');
tempOption.value = '';
this._controls.editor.appendChild(tempOption);
tempOption.selected = true;
}
tempOption.update((text || '').stripScripts().stripTags());
},
checkForExternalText: function() {
this._text = this.getText();
if (this.options.loadTextURL)
this.loadExternalText();
else
this.buildOptionList();
},
loadExternalText: function() {
this.showLoadingText(this.options.loadingText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._text = transport.responseText.strip();
this.buildOptionList();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadTextURL, options);
},
buildOptionList: function() {
this._form.removeClassName(this.options.loadingClassName);
this._collection = this._collection.map(function(entry) {
return 2 === entry.length ? entry : [entry, entry].flatten();
});
var marker = ('value' in this.options) ? this.options.value : this._text;
var textFound = this._collection.any(function(entry) {
return entry[0] == marker;
}.bind(this));
this._controls.editor.update('');
var option;
this._collection.each(function(entry, index) {
option = document.createElement('option');
option.value = entry[0];
option.selected = textFound ? entry[0] == marker : 0 == index;
option.appendChild(document.createTextNode(entry[1]));
this._controls.editor.appendChild(option);
}.bind(this));
this._controls.editor.disabled = false;
Field.scrollFreeActivate(this._controls.editor);
}
});
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
if (!options) return;
function fallback(name, expr) {
if (name in options || expr === undefined) return;
options[name] = expr;
};
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
options.cancelLink == options.cancelButton == false ? false : undefined)));
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
options.okLink == options.okButton == false ? false : undefined)));
fallback('highlightColor', options.highlightcolor);
fallback('highlightEndColor', options.highlightendcolor);
};
Object.extend(Ajax.InPlaceEditor, {
DefaultOptions: {
ajaxOptions: { },
autoRows: 3,                                // Use when multi-line w/ rows == 1
cancelControl: 'link',                      // 'link'|'button'|false
cancelText: 'cancel',
clickToEditText: 'Click to edit',
externalControl: null,                      // id|elt
externalControlOnly: false,
fieldPostCreation: 'activate',              // 'activate'|'focus'|false
formClassName: 'inplaceeditor-form',
formId: null,                               // id|elt
highlightColor: '#ffff99',
highlightEndColor: '#ffffff',
hoverClassName: '',
htmlResponse: true,
loadingClassName: 'inplaceeditor-loading',
loadingText: 'Loading...',
okControl: 'button',                        // 'link'|'button'|false
okText: 'ok',
paramName: 'value',
rows: 1,                                    // If 1 and multi-line, uses autoRows
savingClassName: 'inplaceeditor-saving',
savingText: 'Saving...',
size: 0,
stripLoadedTextTags: false,
submitOnBlur: false,
textAfterControls: '',
textBeforeControls: '',
textBetweenControls: ''
},
DefaultCallbacks: {
callback: function(form) {
return Form.serialize(form);
},
onComplete: function(transport, element) {
new Effect.Highlight(element, {
startcolor: this.options.highlightColor, keepBackgroundImage: true });
},
onEnterEditMode: null,
onEnterHover: function(ipe) {
ipe.element.style.backgroundColor = ipe.options.highlightColor;
if (ipe._effect)
ipe._effect.cancel();
},
onFailure: function(transport, ipe) {
alert('Error communication with the server: ' + transport.responseText.stripTags());
},
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
onLeaveEditMode: null,
onLeaveHover: function(ipe) {
ipe._effect = new Effect.Highlight(ipe.element, {
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
restorecolor: ipe._originalBackground, keepBackgroundImage: true
});
}
},
Listeners: {
click: 'enterEditMode',
keydown: 'checkForEscapeOrReturn',
mouseover: 'enterHover',
mouseout: 'leaveHover'
}
});
Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
Form.Element.DelayedObserver = Class.create({
initialize: function(element, delay, callback) {
this.delay     = delay || 0.5;
this.element   = $(element);
this.callback  = callback;
this.timer     = null;
this.lastValue = $F(this.element); 
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
});
var base_path = document.location.href.replace( /https?:\/\/[^\/]+(\/[^\/#?]+).*/, "$1" );
if( base_path == document.location.href ) {
base_path = '/mydtail';
}
var current_uri = document.location.href.replace( /https?:\/\/[^\/]+(\/[^\/#?]*(\/[^\/#?]*)?).*/, "$1" );
function submitIntegreatedSearch()
{
formObj = $('form_tab_search');
str = $('integreated_search_value').value;
if(str == '' || str == _('Search by Name/Company/School/Location'))
{
alert(_('please fill in a blank'));
$('integreated_search_value').focus();
return false;
}
formObj.submit();
}
function login_try() 
{
if( !$('openid_identifier') ) {
return true;
}
if( $('openid_identifier').default_value ) {
if( $('openid_identifier').default_value == $('openid_identifier').value ) {
$('openid_identifier').value = '';
}
}
if( $('openid_identifier').value == '' ) {
alert( _("Input OpenID or ID issued by IDtail") );
$('openid_identifier').focus();
return false;
}
return true;
}
function post_render() {
$('top_login_button') && Event.observe( $('top_login_button'), 'click', 
function(e){ login_try() && $('login_form').submit(); Event.stop(e); } );
}
function get_cookie(name) {
var variable = name + "=";
var length = variable.length;
var i=-1;
if( (i=document.cookie.indexOf( variable ) ) < 0 )
{
return null;
}
var j = i + variable.length;
var delimeter = document.cookie.indexOf (";", j);
if (delimeter == -1)
delimeter = document.cookie.length;
return unescape(document.cookie.substring(j, delimeter));
}
function draw_menu_desc(str)
{
if( $('menu_description') ) {
$('menu_description').innerHTML = str;
}
}
function show_help_message( input, type, message, submessage )
{
input = $(input);
var help_message_class = 'help_msg';
if( type == 'Negative' ) {
help_message_class = 'help_msg_error';
}
if( !input.message_frame ) {
added = new Insertion.After( input, 
'<div class="' + help_message_class + '" style="display:none;z-index:5">' +
'<div class="edge"></div><span class="b"></span><span></span></div>' );
input.message_frame = $(added.nextSibling);
input.message = $(input.message_frame.firstChild.nextSibling);
input.submessage = $(input.message.nextSibling);
}
if( type != undefined ) {
input.message_frame.className = help_message_class;
}
if( message != undefined ) {
input.message.innerHTML = message;
}
if( submessage != undefined ) {
input.submessage.innerHTML = submessage || '';
}
if( input.message.innerHTML ) {
input.message_frame.show();
if( type != 'Negative' ) {
setTimeout( function() { input.message_frame.hide(); }, 7000 );
}
} else {
input.message_frame.hide();
}
}
function hide_help_message( input, clear )
{
input = $(input);
if( !input.message_frame ) {
return;
}
if( clear ) {
input.message.innerHTML = '';
}
input.message_frame.hide();
}
var keypressed_element = null;
function key_down(e)
{
switch( e.keyCode ) {
case 13:
update_form(e);
Event.stop(e);
keypressed_element = null;
break;
default:
keypressed_element = Event.element(e);
break;
}
}
function update_form_core(f,element,part)
{
values = Form.serialize(f);
if( f.original_values == values ) {
return false;
}
f.original_values = values;
do_ajax( base_path + '/ajax_update', values, part,
{
'onComplete': 
new Effect.Highlight(element, { 
'restorecolor': '#ffffff', 
'startcolor': '#ffdddd', 
'endcolor': '#ffffff'} 
) 
} 
);
return true;
}
function update_form(e)
{
el = Event.element(e);
setTimeout( function() { update_form_core( el.form, el); }, 200 );
}
function update_form_onsubmit(e)
{
var part;
var f = Event.element(e);
var elms = getElementsByIdPattern( 'input', 'refresh_', f );
if( elms.length ) {
part = getIdFragment( elms[0].id );
}
if( !update_form_core(f,f,part) )
{
new Effect.Highlight(f, { 
'restorecolor': '#ffffff', 
'startcolor': '#ddddff', 
'endcolor': '#ffffff'} 
) 
}
Event.stop(e);
}
function del(model, id, part)
{
form = $('form_' + id );
if( form ) {
form.hide();
}
form = $('form_' + model + '_' + id );
if( form ) {
form.hide();
}
do_ajax( base_path + '/ajax_delete/' + model + '/' + id, '' );
}
function add_new(model, type, part)
{
do_ajax( base_path + '/ajax_add_new/' + model + '/' + type, '', part );
}
function update_partial( part )
{
new Ajax.Updater( $(part), base_path + '/ajax_index/' + part , { 'onComplete': postaction_after_load } );
}
function do_ajax(url,postBody,part,complete)
{
show_ajax_hour_glasss( _("Saving...") );
new Ajax.Request( url, { 
'method' : 'post',
'postBody' : postBody,
'onSuccess': function(t,json_obj) 
{
if( typeof complete == 'function' ) {
complete(json_obj);
}
if( part ) {
update_partial( part );
}
show_ajax_hour_glasss( _("Saved") );
setTimeout( hide_ajax_hour_glasss, 4000 );
},
'onFailure': function(t,jso)
{
show_ajax_hour_glasss( _("Failed") );
setTimeout( hide_ajax_hour_glasss, 5000 );
},
'onException': function(t,e)
{
}
});
}
function remove_default_value(e)
{
target = Event.element(e);
if( target.default_value == target.value ) {
target.value = '';
}
}
function set_default_value(e)
{
target = Event.element(e);
target = $(target);
if( e.keyCode != 27 ) {
return;
}
target.value = target.default_value;
Event.stop(e);
}
function set_default_values()
{
inputs = getElementsByIdPattern( 'input', 'default_' );
for( var i = 0; i < inputs.length; i++ )
{
target = $(inputs[i].id.substr(8));
if( !target ) {
continue;
}
target.default_value = target.value = inputs[i].value;
Event.observe( target, 'click', remove_default_value );
Event.observe( target, 'keypress', set_default_value );
}
}
function set_focus_at_first_input()
{
if( window.set_focus_disabled ) {
return;
}
var inputs = document.getElementsByTagName("input");
try {
for( var i = 0; i < inputs.length; i++ )
{
if( $(inputs[i]).visible() && inputs[i].type != 'hidden'  && !inputs[i].readOnly)
{
if( inputs[i].type != 'text' && inputs[i].type != 'password' ) {
break;
}
inputs[i].focus();
if( inputs[i].default_value == inputs[i].value ) {
target.select();
}
break;
}
}} catch(e) {}
}
function set_automatic_update()
{
forms = document.getElementsByTagName( 'form' );
for( var i=0; i<forms.length; i++ ) {
var parasitizable   = false;
var do_not_parasite = false; /* Do not parasite into input element */
var never_parasite  = false;  /* Do not parasite into form submit button */
elms = Form.getInputs( forms[i] );
for( j=0; j<elms.length; j++ ) {
if( elms[j].name.indexOf( '[id]' ) >= 0 ) {
parasitizable = true;
}
if( elms[j].id.indexOf( 'no_ajax' ) >= 0 ) {
do_not_parasite = true; /* submit only */
}
if( elms[j].id.indexOf( 'no_ajax_completely' ) >= 0 ) {
never_parasite = true;
}
}
if( never_parasite ) { continue; }
if( parasitizable ) {
forms[i].original_values = Form.serialize(forms[i]);
Event.observe( forms[i], "submit", update_form_onsubmit );
}
if( !parasitizable || do_not_parasite ) { continue; }
for( j=0; j<elms.length; j++ ) {
if( elms[j].type == 'text' ) {
Event.observe( elms[j], 'blur', update_form );
Event.observe( elms[j], 'keydown', key_down );
}
if( elms[j].type == 'checkbox' || elms[j].type == 'radio' ) {
Event.observe( elms[j], 'click', update_form );
}
}
elms = forms[i].getElementsByTagName( 'select' );
for( j=0; j<elms.length; j++ ) {
Event.observe( elms[j], 'change', update_form );
}
}
}
function toggle_from_label(e)
{
x = Event.element(e);
y = $(x.id.replace( /_label/, '_input' ));
x.hide();
y.show();
y.focus();
}
function do_toggle_from_label(label_id)
{
y = $(label_id.replace( /_label/, '_input' ));
$(label_id).hide();
y.show();
y.focus();
}
function toggle_from_input(e)
{
x = Event.element(e);
y = $(x.id.replace( /_input/, '_label' ));
x.hide();
y.innerHTML = x.value;
y.show();
y.focus();
}
function set_toggle_pair()
{
spans = document.getElementsByTagName( 'span' );
for( var i=0; i<spans.length; i++ ) {
if( spans[i].id.substr(0, 17) == 'toggle_pair_label' ) {
Event.observe( spans[i], 'click', toggle_from_label );
}
}
inputs = document.getElementsByTagName( 'input' );
for( var i=0; i<inputs.length; i++ ) {
if( inputs[i].id.substr(0, 17) == 'toggle_pair_input' ) {
Event.observe( inputs[i], 'blur', toggle_from_input );
}
}
}
function getIdFragment( id )
{
return id.replace( /.*_([^_:]+).*/, "$1" );
}
function getIdFragment2( id )
{
return id.replace( /.*:([^:]+)/, "$1" );
}
function getElementsByIdPattern( tag, pattern, parentElement)
{
if( !parentElement ) {
parentElement = document;
}
elms = parentElement.getElementsByTagName( tag );
len = pattern.length;
var result = new Array();
for( var i=0; i<elms.length; i++ ) {
if( elms[i].id.substr(0, len) == pattern ) {
result.push( elms[i] );
}
}
return result;
}
function hide_ajax_hour_glasss()
{
div = $('save_ing');
if( !div ) return;
document.body.removeChild( div );
}
function show_ajax_hour_glasss(msg)
{
var div;
div = $('save_ing');
if( ! div ) {
div = document.createElement('div');
div.id = 'save_ing';
div.className = 'save_ing';
div.style['display'] = 'block';
var msg_node = document.createElement( 'span' );
var hourglass = document.createElement('img');
hourglass.src = "/img/ico/ico_save.gif";
div.appendChild( hourglass );
div.appendChild( msg_node );
document.body.appendChild( div );
div = $(div);
div.msg_node = msg_node;
div.style.position = 'absolute';
Position.prepare();
}
div.msg_node.innerHTML = msg;
var left = Position.deltaX + (document.documentElement.clientWidth-div.offsetWidth)/2;
var top  = Position.deltaY + (document.documentElement.clientHeight-div.offsetHeight)/2;
div.style.top    = top + 'px';
div.style.left   = left + 'px';
div.show();
}
function hide_message_pannel(e)
{
Event.element(e).parentNode.parentNode.hide();
}
function highlight_flash_message()
{
if( $('msg_pannel_info') ) { new Effect.Highlight('msg_pannel_info', {duration: 3.0}); }
if( $('msg_pannel_warn') ) { new Effect.Highlight('msg_pannel_warn', {duration: 3.0}); }
var buttons = document.getElementsByClassName( 'close' );
if(buttons.length > 0)
{
buttons.each( function(e) { Event.observe( e, 'click', hide_message_pannel ); } );
}
}
function set_default_loginid()
{
setTimeout( function() {
var openid_identifier = $('openid_identifier');
var last_loginid = get_cookie('idtail');
if( !openid_identifier || !last_loginid ) {
return;
}
$('openid_identifier').value = last_loginid;
}, 200 );
}
function postaction_after_load()
{
set_default_values();
set_default_loginid();
if( window.page_onload ) window.page_onload(); 
post_render();
set_focus_at_first_input();
set_automatic_update();
set_toggle_pair();
highlight_flash_message();
set_rec_network_list();
}
function preaction_before_unload()
{
if( window.page_onunload ) window.page_onunload(); 
}
function debug_dump(e,ret)
{
var b = "";
var c = 0;
var i = 0;
if( typeof e == 'string' ) {
e = $(e);
}
for( a in e ) {
i++;
if( typeof e[a] == 'function' ) {
b += i + ". " + a + " : FUNCTION\r\n";
} else {
v = (e[a]+'');
if( v.length > 100 ) v = v.substr(0,100)+"...";
b += i + ". " + a + " : " + v + "\r\n";
}
if( c > 40 ) {
c = 0;
if( ret == undefined ) {
alert(b);
b = '';
}
} else {
c++;
}
}
if( c != 0 ) {
if( ret == undefined ) {
alert(b);
} else {
return b;
}
}
return '';
}
if( window.console == undefined ) {
function _log(msg) {
var log = document.getElementById('log');
if( !log ) return;
log.innerHTML += msg + "<br />";
}
window.console = { 'info': _log, 'warn': _log, 'error': _log, 'log': _log };
}
function set_rec_network_list()
{
recNetwork = $('recommend_network_list');
if(recNetwork != null)
{
new Ajax.Updater('recommend_network_list', "/recommend/ajax_get_network_list" , {method:'get'});
}	
}
var checkbox_check_value = true;
function select_all_checkbox(FormName, FieldName)
{
if(!document.forms[FormName])
{
return;
}
var objCheckBoxes = document.forms[FormName].elements[FieldName];
if(!objCheckBoxes)
{
return;
}
var countCheckBoxes = objCheckBoxes.length;
if(!countCheckBoxes)
{
objCheckBoxes.checked = checkbox_check_value;
}
else
{
for(var i = 0; i < countCheckBoxes; i++)
objCheckBoxes[i].checked = checkbox_check_value;
}
checkbox_check_value = !checkbox_check_value;
}
function hasCheckedCheckbox(formName, FieldName)
{
try {
var chkBoxes = $(formName).getInputs('checkbox', FieldName);
for(var i = 0; i < chkBoxes.length; i++)
{
if( chkBoxes[i].checked == true)
{
return true;
}
}
return false;
} catch(e) {
return false;
}
}
function check_is_not_blank(obj)
{
if(obj.value.length == 0)
{
alert(_('please fill in a blank'));
obj.focus();
return false;
}
return true;
}
function editable_toggle(e)
{
e = Event.element(e);
e.hide();
var p = e.related_pair;
if( p.host == true ) {
p.innerHTML = e.value;
}
p.show();
p.focus();
}
function select_li(li,notouch_focus)
{
li.hide();
li.focussed = true;
li.related_pair.show();
if( notouch_focus == undefined ) {
li.related_pair.focus();
}
}
function unselect_li(li)
{
li.related_pair.hide();
li.show();
li.focussed = false;
}
function editable_get_focus(e)
{
element = Event.element(e);
editable_toggle(e);
$A(element.parentNode.childNodes).map( 
function(li) { 
if( li.nodeName.toUpperCase() == 'LI' && element != li ) {
li.innerHTML = li.related_pair.value + " ";
unselect_li(li);
} 
}
);
}
function editable_blur(e)
{
element = Event.element(e);
element.related_pair.innerHTML = element.value + " ";
}
function editable(e,edit_group, callback_keypress, callback_upate)
{
if( !$(e) || e.related_pair != undefined ) {
return;
}
e = $(e);
e.host = true;
var inp = document.createElement( 'input' );
e.related_pair = inp;
inp.related_pair = e;
inp.type = 'text';
inp.value = e.innerHTML.strip();
inp.host = false;
inp.edit_group = edit_group;
$(inp).addClassName( 'input_txt' );
$(inp).setStyle( 'display:inline; font:12px' );
$(inp).addClassName( edit_group );
$(inp).hide();
e.parentNode.insertBefore( inp, e );
Event.observe( e, 'click', editable_get_focus );
Event.observe( inp, 'blur', editable_blur );
if( callback_upate != undefined ) {
Event.observe( inp, 'blur', callback_upate );
}
if( callback_keypress != undefined ) {
Event.observe( inp, 'keypress', callback_keypress );
}
}
function encode_url_utf8(str)
{
if(!str) return "";
var result, i, s, u;
result = "";
for(i=0; i<str.length; i++)
{
s = str.charAt(i);
u = str.charCodeAt(i);
if(s == " ")
{
result += "+";
}
else
{
if(u == 0x2a || u == 0x2d || u == 0x2e || u == 0x5f || ((u >= 0x30) && (u <= 0x39)) || ((u >= 0x41) && (u <= 0x5a)) || ((u >= 0x61) && (u <= 0x7a)))
{
result = result + s;
}
else
{
if ((u >= 0x0) && (u <= 0x7f))
{
s = "0"+u.toString(16);
result += "%"+ s.substr(s.length-2);
}
else if (u > 0x1fffff)
{
result += "%" + (oxf0 + ((u & 0x1c0000) >> 18)).toString(16);
result += "%" + (0x80 + ((u & 0x3f000) >> 12)).toString(16);
result += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
result += "%" + (0x80 + (u & 0x3f)).toString(16);
}
else if (u > 0x7ff)
{
result += "%" + (0xe0 + ((u & 0xf000) >> 12)).toString(16);
result += "%" + (0x80 + ((u & 0xfc0) >> 6)).toString(16);
result += "%" + (0x80 + (u & 0x3f)).toString(16);
}
else
{
result += "%" + (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
result += "%" + (0x80 + (u & 0x3f)).toString(16);
}
} // end of if
} // end of if
} // end of for
return result;
}
function str_replace(search_str, replace_str, str)
{
var intIndexOfMatch = str.indexOf( search_str );
while (intIndexOfMatch != -1){
str = str.replace( search_str, replace_str )
intIndexOfMatch = str.indexOf( search_str );
}
return str;
}
function do_accelerate_key(e)
{
var tagName = Event.element(e).tagName;
if( tagName == "INPUT" || tagName == "TEXTAREA" ) {
return;
}
var domain_s = document.location.href.replace( /https?:\/\/[^.]+(\.[^\/]+).*/, "https://www$1" );
var domain = document.location.href.replace( /(https?:\/\/)[^.]+(\.[^\/]+).*/, "$1www$2" );
if( e.charCode == 113 ) { /* Q */
if( !$('openid_identifier') ) {
return;
}
document.location.href = domain_s+"/login?redirect="+escape(document.location.href);
}
else if( e.charCode == 119 ) { /* W */
document.location.href = domain+"/network";
}
else if( e.charCode == 101 ) { /* E */
document.location.href = domain+"/mydtail";
}
else if( e.charCode == 97 ) { /* A */
document.location.href = domain+"/play";
}
else if( e.charCode == 115 ) { /* S */
document.location.href = domain+"/photos";
}
else if( e.charCode == 118 ) { /* V */
document.location.href = domain+"/antenna";
}
}
function onRequestNetwork(receiver_id, callingObj)
{
if(receiver_id == null)
{
return false;
}
var URL = "/network/ajax_get_sendable_code/" + receiver_id;
new Ajax.Request(URL, {  
onSuccess: function(xmlHttp)
{
onCompleteRequestNetwork(xmlHttp.responseText, callingObj);
}
});
}
function onCompleteRequestNetwork(resultObj, callingObj)
{
var result = eval( '(' + resultObj + ')');
if(result['sendable'] == true)
{
var receiver_id = result['receiver_id'];
var returnUrl = encodeURIComponent(window.location);
var requestUrl = '/network/send?receiver_id=' + receiver_id + '&returnUrl=' + returnUrl;
if(callingObj != null)
{
lightbox(requestUrl, {width:380, height:300, top:20, left:20, position:'relative', callingObj:callingObj});
}
else
{
lightbox(requestUrl, {width:380, height:300, top:420, left:130, position:'absolute'});
}
}
else
{
location.reload(true);
}
}
function sendNoteWithReturnUrl(receiver_id, currentObj)
{
var returnUrl = encodeURIComponent(window.location);
lightbox('/notes/send_with_url?returnUrl=' + returnUrl + "&receiver_id=" + receiver_id, {width:400, height:250, left:20, top:20, callingObj:currentObj});
}
try {
Event.observe( window, 'load', postaction_after_load );
Event.observe( window, 'unload', preaction_before_unload );
Event.observe( document, 'keypress', do_accelerate_key );
} catch(e) { /* Is there no prototype.js loaded? */ }
if(typeof(Control) == "undefined")
Control = {};
Control.Modal = Class.create();
Object.extend(Control.Modal,{
loaded: false,
loading: false,
loadingTimeout: false,
overlay: false,
container: false,
current: false,
ie: false,
effects: {
containerFade: false,
containerAppear: false,
overlayFade: false,
overlayAppear: false
},
targetRegexp: /#(.+)$/,
imgRegexp: /\.(jpe?g|gif|png|tiff?)$/i,
overlayStyles: {
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
zIndex: 9998
},
overlayIEStyles: {
position: 'absolute',
top: 0,
left: 0,
zIndex: 9998
},
disableHoverClose: false,
load: function(){
if(!Control.Modal.loaded){
Control.Modal.loaded = true;
Control.Modal.ie = !(typeof document.body.style.maxHeight != 'undefined');
Control.Modal.overlay = $(document.createElement('div'));
Control.Modal.overlay.id = 'modal_overlay';
Object.extend(Control.Modal.overlay.style,Control.Modal['overlay' + (Control.Modal.ie ? 'IE' : '') + 'Styles']);
Control.Modal.overlay.hide();
Control.Modal.container = $(document.createElement('div'));
Control.Modal.container.id = 'modal_container';
Control.Modal.container.hide();
Control.Modal.loading = $(document.createElement('div'));
Control.Modal.loading.id = 'modal_loading';
Control.Modal.loading.hide();
var body_tag = document.getElementsByTagName('body')[0];
body_tag.appendChild(Control.Modal.overlay);
body_tag.appendChild(Control.Modal.container);
body_tag.appendChild(Control.Modal.loading);
Control.Modal.container.observe('mouseout',function(event){
if(!Control.Modal.disableHoverClose && Control.Modal.current && Control.Modal.current.options.hover && !Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
Control.Modal.close();
});
}
},
open: function(contents,options){
options = options || {};
if(!options.contents)
options.contents = contents;
var modal_instance = new Control.Modal(false,options);
modal_instance.open();
return modal_instance;
},
close: function(force){
if(typeof(force) != 'boolean')
force = false;
if(Control.Modal.current)
Control.Modal.current.close(force);
},
attachEvents: function(){
Event.observe(window,'load',Control.Modal.load);
Event.observe(window,'unload',Event.unloadCache,false);
},
center: function(element){
if(!element._absolutized){
element.setStyle({
position: 'absolute'
}); 
element._absolutized = true;
}
var dimensions = element.getDimensions();
Position.prepare();
var offset_left = (Position.deltaX + Math.floor((Control.Modal.getWindowWidth() - dimensions.width) / 2));
var offset_top = (Position.deltaY + ((Control.Modal.getWindowHeight() > dimensions.height) ? Math.floor((Control.Modal.getWindowHeight() - dimensions.height) / 2) : 0));
element.setStyle({
top: ((dimensions.height <= Control.Modal.getDocumentHeight()) ? ((offset_top != null && offset_top > 0) ? offset_top : '0') + 'px' : 0),
left: ((dimensions.width <= Control.Modal.getDocumentWidth()) ? ((offset_left != null && offset_left > 0) ? offset_left : '0') + 'px' : 0)
});
},
getWindowWidth: function(){
return (self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0);
},
getWindowHeight: function(){
return (self.innerHeight ||  document.documentElement.clientHeight || document.body.clientHeight || 0);
},
getDocumentWidth: function(){
return Math.min(document.body.scrollWidth,Control.Modal.getWindowWidth());
},
getDocumentHeight: function(){
return Math.max(document.body.scrollHeight,Control.Modal.getWindowHeight());
},
onKeyDown: function(event){
if(event.keyCode == Event.KEY_ESC)
Control.Modal.close();
}
});
Object.extend(Control.Modal.prototype,{
mode: '',
html: false,
href: '',
element: false,
src: false,
imageLoaded: false,
ajaxRequest: false,
initialize: function(element,options){
this.element = $(element);
this.options = {
beforeOpen: Prototype.emptyFunction,
afterOpen: Prototype.emptyFunction,
beforeClose: Prototype.emptyFunction,
afterClose: Prototype.emptyFunction,
onSuccess: Prototype.emptyFunction,
onFailure: Prototype.emptyFunction,
onException: Prototype.emptyFunction,
beforeImageLoad: Prototype.emptyFunction,
afterImageLoad: Prototype.emptyFunction,
autoOpenIfLinked: true,
contents: false,
loading: false, //display loading indicator
fade: false,
fadeDuration: 0.75,
image: false,
imageCloseOnClick: true,
hover: false,
iframe: false,
iframeTemplate: new Template('<iframe src="#{href}" width="100%" height="100%" frameborder="0" scrolling="no" id="#{id}"></iframe>'),
evalScripts: true, //for Ajax, define here instead of in requestOptions
requestOptions: {}, //for Ajax.Request
overlayDisplay: true,
overlayClassName: '',
overlayCloseOnClick: true,
containerClassName: '',
opacity: 0.3,
zIndex: 9998,
width: null,
height: null,
offsetLeft: 0, //for use with 'relative'
offsetTop: 0, //for use with 'relative'
position: 'absolute' //'absolute' or 'relative'
};
Object.extend(this.options,options || {});
var target_match = false;
var image_match = false;
if(this.element){
target_match = Control.Modal.targetRegexp.exec(this.element.href);
image_match = Control.Modal.imgRegexp.exec(this.element.href);
}
if(this.options.position == 'mouse')
this.options.hover = true;
if(this.options.contents){
this.mode = 'contents';
}else if(this.options.image || image_match){
this.mode = 'image';
this.src = this.element.href;
}else if(target_match){
this.mode = 'named';
var x = $(target_match[1]);
this.html = x.innerHTML;
x.remove();
this.href = target_match[1];
}else{
this.mode = (this.options.iframe) ? 'iframe' : 'ajax';
this.href = this.element.href;
}
if(this.element){
if(this.options.hover){
this.element.observe('mouseover',this.open.bind(this));
this.element.observe('mouseout',function(event){
if(!Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
this.close();
}.bindAsEventListener(this));
}else{
this.element.onclick = function(event){
this.open();
Event.stop(event);
return false;
}.bindAsEventListener(this);
}
}
var targets = Control.Modal.targetRegexp.exec(window.location);
this.position = function(event){
if(this.options.position == 'absolute')
Control.Modal.center(Control.Modal.container);
else{
var xy = (event && this.options.position == 'mouse' ? [Event.pointerX(event),Event.pointerY(event)] : Position.cumulativeOffset(this.element));
Control.Modal.container.setStyle({
position: 'absolute',
top: xy[1] + (typeof(this.options.offsetTop) == 'function' ? this.options.offsetTop() : this.options.offsetTop) +(20) + 'px',
left: xy[0] + (typeof(this.options.offsetLeft) == 'function' ? this.options.offsetLeft() : this.options.offsetLeft) + 'px'
});
}
if(Control.Modal.ie){
Control.Modal.overlay.setStyle({
height: Control.Modal.getDocumentHeight() + 'px',
width: Control.Modal.getDocumentWidth() + 'px'
});
}
}.bind(this);
if(this.mode == 'named' && this.options.autoOpenIfLinked && targets && targets[1] && targets[1] == this.href)
this.open();
},
showLoadingIndicator: function(){
if(this.options.loading){
Control.Modal.loadingTimeout = window.setTimeout(function(){
var modal_image = $('modal_image');
if(modal_image)
modal_image.hide();
Control.Modal.loading.style.zIndex = this.options.zIndex + 1;
Control.Modal.loading.update('<img id="modal_loading" src="' + this.options.loading + '"/>');
Control.Modal.loading.show();
Control.Modal.center(Control.Modal.loading);
}.bind(this),250);
}
},
hideLoadingIndicator: function(){
if(this.options.loading){
if(Control.Modal.loadingTimeout)
window.clearTimeout(Control.Modal.loadingTimeout);
var modal_image = $('modal_image');
if(modal_image)
modal_image.show();
Control.Modal.loading.hide();
}
},
open: function(force){
if(!force && this.notify('beforeOpen') === false)
return;
if(!Control.Modal.loaded)
Control.Modal.load();
Control.Modal.close();
if(!this.options.hover)
Event.observe($(document.getElementsByTagName('body')[0]),'keydown',Control.Modal.onKeyDown);
Control.Modal.current = this;
if(!this.options.hover)
Control.Modal.overlay.setStyle({
zIndex: this.options.zIndex,
opacity: this.options.opacity
});
Control.Modal.container.setStyle({
zIndex: this.options.zIndex + 1,
width: (this.options.width ? (typeof(this.options.width) == 'function' ? this.options.width() : this.options.width) + 'px' : null),
height: (this.options.height ? (typeof(this.options.height) == 'function' ? this.options.height() : this.options.height) + 'px' : null)
});
if(Control.Modal.ie && !this.options.hover){
$A(document.getElementsByTagName('select')).each(function(select){
select.style.visibility = 'hidden';
});
}
Control.Modal.overlay.addClassName(this.options.overlayClassName);
Control.Modal.container.addClassName(this.options.containerClassName);
switch(this.mode){
case 'image':
this.imageLoaded = false;
this.notify('beforeImageLoad');
this.showLoadingIndicator();
var img = document.createElement('img');
img.onload = function(img){
this.hideLoadingIndicator();
this.update([img]);
if(this.options.imageCloseOnClick)
$(img).observe('click',Control.Modal.close);
this.position();
this.notify('afterImageLoad');
img.onload = null;
}.bind(this,img);
img.src = this.src;
img.id = 'modal_image';
break;
case 'ajax':
this.notify('beforeLoad');
var options = {
method: 'post',
onSuccess: function(request){
this.hideLoadingIndicator();
this.update(request.responseText);
this.notify('onSuccess',request);
this.ajaxRequest = false;
}.bind(this),
onFailure: function(){
this.notify('onFailure');
}.bind(this),
onException: function(){
this.notify('onException');
}.bind(this)
};
Object.extend(options,this.options.requestOptions);
this.showLoadingIndicator();
this.ajaxRequest = new Ajax.Request(this.href,options);
break;
case 'iframe':
this.update(this.options.iframeTemplate.evaluate({href: this.href, id: 'modal_iframe'}));
break;
case 'contents':
this.update((typeof(this.options.contents) == 'function' ? this.options.contents() : this.options.contents));
break;
case 'named':
this.update(this.html);
break;
}
if(!this.options.hover){
if(this.options.overlayCloseOnClick && this.options.overlayDisplay)
Control.Modal.overlay.observe('click',Control.Modal.close);
if(this.options.overlayDisplay){
if(this.options.fade){
if(Control.Modal.effects.overlayFade)
Control.Modal.effects.overlayFade.cancel();
try{
Control.Modal.effects.overlayAppear = new Effect.Appear(Control.Modal.overlay,{
queue: {
position: 'front',
scope: 'Control.Modal'
},
to: this.options.opacity,
duration: this.options.fadeDuration / 2000
});
}catch(e){
}
}else
Control.Modal.overlay.show();
}
}
if(this.options.position == 'mouse'){
this.mouseHoverListener = this.position.bindAsEventListener(this);
this.element.observe('mousemove',this.mouseHoverListener);
}
this.notify('afterOpen');
},
update: function(html){
if(typeof(html) == 'string')
Control.Modal.container.update(html);
else{
Control.Modal.container.update('');
(html.each) ? html.each(function(node){
Control.Modal.container.appendChild(node);
}) : Control.Modal.container.appendChild(node);
}
if(this.options.fade){
if(Control.Modal.effects.containerFade)
Control.Modal.effects.containerFade.cancel();
Control.Modal.container.show();
try{
Control.Modal.effects.containerAppear = new Effect.Appear(Control.Modal.container,{
queue: {
position: 'end',
scope: 'Control.Modal'
},
to: 1,
duration: this.options.fadeDuration /2000
});
}catch(e){
}
}else
Control.Modal.container.show();
this.position();
Event.observe(window,'resize',this.position,false);
Event.observe(window,'scroll',this.position,false);
},
close: function(force){
if(!force && this.notify('beforeClose') === false)
return;
if(this.ajaxRequest)
this.ajaxRequest.transport.abort();
this.hideLoadingIndicator();	
if(this.mode == 'image'){
var modal_image = $('modal_image');
if(this.options.imageCloseOnClick && modal_image)
modal_image.stopObserving('click',Control.Modal.close);
}
if(Control.Modal.ie && !this.options.hover){
$A(document.getElementsByTagName('select')).each(function(select){
select.style.visibility = 'visible';
});			
}
if(!this.options.hover)
Event.stopObserving(window,'keyup',Control.Modal.onKeyDown);
Control.Modal.current = false;
Event.stopObserving(window,'resize',this.position,false);
Event.stopObserving(window,'scroll',this.position,false);
if(!this.options.hover){
if(this.options.overlayCloseOnClick && this.options.overlayDisplay)
Control.Modal.overlay.stopObserving('click',Control.Modal.close);
if(this.options.overlayDisplay){
if(this.options.fade){
if(Control.Modal.effects.overlayAppear)
Control.Modal.effects.overlayAppear.cancel();
Control.Modal.overlay.hide();
}else
Control.Modal.overlay.hide();
}
}
if(this.options.fade){
if(Control.Modal.effects.containerAppear)
Control.Modal.effects.containerAppear.cancel();
Control.Modal.effects.containerFade = new Effect.SwitchOff(Control.Modal.container,{
duration: this.options.fadeDuration / 100
});
}else{
Control.Modal.container.hide();
Control.Modal.container.update('');
this.resetClassNameAndStyles();
}
if(this.options.position == 'mouse')
this.element.stopObserving('mousemove',this.mouseHoverListener);
this.notify('afterClose');
},
resetClassNameAndStyles: function(){
Control.Modal.overlay.removeClassName(this.options.overlayClassName);
Control.Modal.container.removeClassName(this.options.containerClassName);
Control.Modal.container.setStyle({
height: null,
width: null,
top: null,
left: null
});
},
notify: function(event_name){
try{
if(this.options[event_name])
return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
}catch(e){
if(e != $break)
throw e;
else
return false;
}
}
});
if(typeof(Object.Event) != 'undefined')
Object.Event.extend(Control.Modal);
Control.Modal.attachEvents();
Effect.SwitchOff = function(element) {
element = $(element);
element.setStyle({opacity: 1});
var oldOpacity = 0;
return new Effect.Appear(element, Object.extend({
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
new Effect.Scale(effect.element, 1, { 
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) { 
effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
}
}, arguments[1] || { }));
};
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
to:   1.0,
afterFinishInternal: function(effect) {
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from).show(); 
}}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
var loadingImgSrc = '/img/ico/loading.gif'
function getPageScroll(){
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
arrayPageScroll = new Array('',yScroll) 
return arrayPageScroll;
}
function getPageSize(){
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {	
xScroll = document.body.scrollWidth;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) {	// all except Explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}	
if (yScroll < windowHeight){
pageHeight = windowHeight;
} else { 
pageHeight = yScroll;
}
if (xScroll < windowWidth) {	
pageWidth = windowWidth;
} else {
pageWidth = xScroll;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) ;
return arrayPageSize;
}
function getAbsoluteObjectX(obj) {
var x = obj.offsetLeft;
while (obj.offsetParent) {
obj = obj.offsetParent;
x += obj.offsetLeft;
}
return(x);
}
function getAbsoluteObjectY(obj) {
var y = obj.offsetTop;
while (obj.offsetParent) {
obj = obj.offsetParent;
y += obj.offsetTop;
}
return(y);
}
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();
if (key == 'x') hideLightbox();
}
function listenKey () {	document.onkeypress = getKey; }
function showLightbox() {
var objOverlay = document.getElementById('overlay');
var objLightbox = document.getElementById('lightbox');
var objLoadingImage = document.getElementById('loadingImage');
if( lbOverflow ) {
objLightbox.style.overflow = lbOverflow;
}
if( lbOverflowX ) {
objLightbox.style['overflow-x'] = lbOverflowX;
}
if( lbOverflowY ) {
objLightbox.style['overflow-y'] = lbOverflowY;
}
objLoadingImage.style.display = 'none';
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
if (lbH!=undefined) objLightbox.style.height = lbH + "px";
if (lbW!=undefined) objLightbox.style.width = lbW + "px";
if (lbY==undefined) {lbY=20;}
objLightbox.style.top = lbY + "px";
objLightbox.style.visibility = 'hidden';
objLightbox.style.display = 'block';
if (lbX==undefined) {lbX = ((arrayPageSize[0] - objLightbox.offsetWidth) / 2);}
objLightbox.style.left = lbX + "px";
objLightbox.style.visibility = 'visible';
arrayPageSize = getPageSize();
objOverlay.style.height = (arrayPageSize[1] + 'px');
listenKey();
}
var lbX, lbY, lbW, lbH, lbOverflow, lbOverflowX, lbOverflowY;
function lightbox(target, P) {
if (target==undefined) return;
if (P==undefined) {var P = new Object();}
var params = P.params; var h = P.height; var w = P.width; var x = P.left; var y = P.top; var callingObj = P.callingObj; var position = P.position; var overflow = P.overflow;
if (params==undefined) {params = '';}
if (overflow==undefined) {overflow = 'auto';}
if (position==undefined) {position = 'relative';} // original default position was 'absolute'
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
if (position=="relative") {
if (!callingObj) {alert('Lightbox needs a callingObj when positioning relatively');}
if (x==undefined) x=10;
if (y==undefined) y=10;
x += getAbsoluteObjectX(callingObj);
y += getAbsoluteObjectY(callingObj);
} else {
if (y==undefined) y=20;
y += arrayPageScroll[1];
}
lbX = x;
lbY = y;
lbW = w;
lbH = h;
lbOverflow = overflow;
lbOverflowX = P['overflowX'];
lbOverflowY = P['overflowY'];
if( lbOverflowX || lbOverflowY ) {
lbOverflow = '';
}
initLightbox();
var objOverlay = document.getElementById('overlay');
var objLightbox = document.getElementById('lightbox');
var objLoadingImage = document.getElementById('loadingImage');
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
objLoadingImage.style.display = 'block';
objLoadingImage.style.visibility = 'hidden';
objOverlay.style.height = (arrayPageSize[1] + 'px');
objOverlay.style.display = 'block';
if( P.targetIsHtml == undefined ) {
new Ajax.Updater('lightbox', target, {method: 'get', parameters: params, evalScripts: true, 
onComplete: function() { if( P.onComplete != undefined ) { P.onComplete(P); } showLightbox(); } });
} else {
$('lightbox').innerHTML =  target;
showLightbox();
}
}
function hideLightbox()
{
var objOverlay = document.getElementById('overlay');
var objLightbox = document.getElementById('lightbox');
var objLoadingImage = document.getElementById('loadingImage');
objOverlay.style.display = 'none';
objLightbox.style.display = 'none';
objLoadingImage.style.display = 'none';
document.onkeypress = '';
}
function initLightbox()
{
var objBody = document.getElementsByTagName("body").item(0);
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
if (!document.getElementById('overlay')) {
var objOverlay = document.createElement("div");
objOverlay.setAttribute('id','overlay');
objOverlay.onclick = function () {hideLightbox(); return false;}
objOverlay.style.display = 'none';
objOverlay.style.position = 'absolute';
objOverlay.style.top = '0';
objOverlay.style.left = '0';
objOverlay.style.zIndex = '90';
objOverlay.style.width = '100%';
objBody.insertBefore(objOverlay, objBody.firstChild);
}	
if (!document.getElementById('lightbox')) {
var objLightbox = document.createElement("div");
objLightbox.setAttribute('id','lightbox');
objLightbox.style.display = 'none';
objLightbox.style.position = 'absolute';
objLightbox.style.zIndex = '100';	
objBody.insertBefore(objLightbox, objOverlay.nextSibling);
}
if (!document.getElementById('loadingImage')) {
var objLoadingImage = document.createElement("img");
objLoadingImage.src = loadingImgSrc;
objLoadingImage.setAttribute('id','loadingImage');
objLoadingImage.style.position = 'absolute';
objLoadingImage.style.zIndex = '150';
objBody.insertBefore(objLoadingImage, objBody.firstChild);
}
}
function Nethru_getCookieVal(offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function Nethru_SetCookie(name, value){
var argv = Nethru_SetCookie.arguments;
var argc = Nethru_SetCookie.arguments.length;
var expires = (2 < argc) ? argv[2] : null;
var path = (3 < argc) ? argv[3] : null;
var domain = (4 < argc) ? argv[4] : null;
var secure = (5 < argc) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires="+expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function Nethru_GetCookie(name){
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen)
{
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return Nethru_getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0)
break;
}
return null;
}
function Nethru_makePersistentCookie(name,length,path,domain)
{
var today = new Date();
var expiredDate = new Date(2011,1,1);
var cookie;
var value;
cookie = Nethru_GetCookie(name);
if ( cookie ) {
return 1;
}
var values = new Array();
for ( i=0; i < length ; i++ ) {
values[i] = "" + Math.random();
}
value = today.getTime();
for ( i=0; i < length ; i++ ) {
value += values[i].charAt(2);
}
Nethru_SetCookie(name,value,expiredDate,path,domain);
}
function Nethru_getDomain() {
var _host   = document.domain;
var so      = _host.split('.');
var dm    = so[so.length-2] + '.' + so[so.length-1];
return (so[so.length-1].length == 2) ? so[so.length-3] + '.' + dm : dm;
}
var Nethru_domain  = Nethru_getDomain();
Nethru_makePersistentCookie("PCID",10,"/",Nethru_domain);
function get_navi_num(e_id)
{
return e_id.substr(e_id.indexOf('navi_') + 5 , 2);
}
function gnb_on_over_navi(e_id)
{
var num = get_navi_num(e_id);
show_subnavi(num);
}
function gnb_on_out_navi(e_id)
{
var num = get_navi_num(e_id);
hide_subnavi(num);
}
function gnb_on_over_subnavi(e_id)
{
var num = get_navi_num(e_id);
show_subnavi(num);
}
function gnb_on_out_subnavi(e_id)
{
var num = get_navi_num(e_id);
hide_subnavi(num);
}
function show_subnavi(num)
{
element_id = 'subnavi_' + num;
obj = document.getElementById(element_id);
obj.style.display = "block";
obj.style.zIndex = "9999";
navi_arrow_up(num);
}
function hide_subnavi(num)
{
element_id = 'subnavi_' + num;
obj = document.getElementById(element_id);
obj.style.display = "none";
navi_arrow_down(num);
}
function navi_arrow_up(num)
{
arrow_id = 'img_navi_' + num;
document.getElementById(arrow_id).style.display = 'none';
document.getElementById(arrow_id + '_on').style.display = '';
}
function navi_arrow_down(num)
{
arrow_id = 'img_navi_' + num;
document.getElementById(arrow_id).style.display = '';
document.getElementById(arrow_id + '_on').style.display = 'none';
}
function on_click_mydtail_link(url)
{
window.location.href = url;
}
function on_over_mydtail_link()
{
obj = document.getElementById('mydtail_link');
obj.style.cursor = 'pointer';
obj.style.textDecoration = 'underline';
}
function on_out_mydtail_link()
{
obj = document.getElementById('mydtail_link');
obj.style.cursor = 'none';
obj.style.textDecoration = 'none';
}
if( window.idtail_base_url == undefined ) {
if( window.base_path == undefined ) {
idtail_base_url = "http://www.idtail.com";
} else {
idtail_base_url = "";
}
}
window.default_icon = idtail_base_url+"/icon/default/160x160";
if( window.IDtailPhotoNav == undefined ) {
window.IDtailPhotoNav = function (options, debuginfo)
{
this.debuginfo = debuginfo || 'Photo navigation';
this.coords = new Array();
this.lazy_freq = 0.3;
this.freq = 0.05;
this.move_complete_count = 8;
this.move_count = -1;
this.view_count = options['view_count'] || 1;
this.options = options;
this.frame = options.frame;
this.image_width  = parseFloat(options.image_width);
this.image_height = parseFloat(options.image_height);
this.imageframe_width  = parseFloat(options.imageframe_width);
this.imageframe_height = parseFloat(options.imageframe_height);
this.imageframe_width_unit  = options.imageframe_width.substr(options.imageframe_width.length-2);
this.imageframe_height_unit = options.imageframe_height.substr(options.imageframe_height.length-2);
this.image_style = {border:options['border'],padding:options['image_padding'],width:options['image_width'],height:options['image_height']};
this.timer_handle = null;
this.lazy_timer_handle = null;
this.pane = $(options.pane);
this.seemore = $(options.seemore);
this.prev = $(options.prev);
this.next = $(options.next);
this.close = $(options.close);
window.default_icon = idtail_base_url+"/icon/default/160x160";
if( !this.prev ) {
alert( "Not found: " + options.prev );
}
if( !this.next ) {
alert( "Not found: " + options.next );
}
}
function idtail_add_gray_screen()
{
if( IDtailPhotoNav.gray_screen ) return IDtailPhotoNav.gray_screen;
IDtailPhotoNav.gray_screen = $(document.createElement("div"));
IDtailPhotoNav.gray_screen.hide();
document.body.appendChild( IDtailPhotoNav.gray_screen );
IDtailPhotoNav.gray_screen.observe( 'click', idtail_hide_all_large_panes );
return IDtailPhotoNav.gray_screen;
}
function idtail_hide_all_large_panes(e)
{
Event.stop(e);
IDtailPhotoNav.large_panes.map( function(nav){nav.hide();} );
idtail_hide_gray_screen();
}
function idtail_show_gray_screen()
{
var w = window;
Position.absolutize(IDtailPhotoNav.gray_screen);
IDtailPhotoNav.gray_screen.style.top = 0;
IDtailPhotoNav.gray_screen.style.left = 0;
IDtailPhotoNav.gray_screen.style.width = 
(w.document.documentElement.scrollWidth  || w.document.body.clientWidth) + "px";
IDtailPhotoNav.gray_screen.style.height = 
(w.document.documentElement.scrollHeight || w.document.body.clientHeight) + "px";
IDtailPhotoNav.gray_screen.style.zIndex = 98;
IDtailPhotoNav.gray_screen.setStyle( { 'background-color':'rgb(238,238,238)', filter:'alpha(opacity=80)', 'opacity':.8} );
IDtailPhotoNav.gray_screen.show();
}
function idtail_hide_gray_screen()
{
IDtailPhotoNav.gray_screen.hide();
}
Object.extend( IDtailPhotoNav.prototype, {
onclick_prev: function(e)
{
Event.stop(e);
this.move_left();
},
onclick_next: function(e)
{
Event.stop(e);
this.move_right();
},
onclick_close: function(e)
{
Event.stop(e);
this.hide();
},
real_coord: function (index)
{
var t = parseFloat(index)*this.imageframe_width;
t = Math.round(t*100)/100;
return (-t)+this.imageframe_width_unit;
},
push_coords: function( inc )
{
var beg = 1;
var end = this.move_complete_count;
var step = inc/Math.abs(inc);
var tmp_coords = new Array();
for( var i=beg; i<=end; i++ ) {
coord = this.real_coord( this.target+inc*(i/this.move_complete_count) );
tmp_coords.push( coord );
}
this.target += inc;
if( this.target == this.images.length+this.view_count-1 ) {
this.target = this.view_count-1;
tmp_coords.push( this.real_coord(this.target) );
} else if( this.target == -this.view_count ) {
this.target = this.images.length - this.view_count;
tmp_coords.push( this.real_coord(this.target) );
}
this.coords = tmp_coords.reverse().concat( this.coords );
},
load_images: function(index)
{
if( index == undefined ) {
for(var i=0; i<this.images.length;i++) this.load_images(i);
return;
}
if( !this.img_refs[index].birth ) {
this.img_refs[index].src = this.img_refs[index].img_src;
this.img_refs[index].birth = true;
if( index-this.images.length >= this.index_begin ) {
this.img_refs[index-this.images.length].src = this.img_refs[index-this.images.length].img_src;
this.img_refs[index-this.images.length].birth = true;
}
if( index+this.images.length < this.index_end ) {
this.img_refs[index+this.images.length].src = this.img_refs[index+this.images.length].img_src;
this.img_refs[index+this.images.length].birth = true;
}
}
},
move_left: function()
{
this.push_coords( -1 );
this.update_seemore();
},
move_right: function()
{
this.push_coords( +1 );
this.update_seemore();
},
update_seemore: function()
{
if( !$(this.options['seemore']) ) return;
if( this.real_count == 0 ) {
$(this.options['seemore']).innerHTML = "0 / 0";
} else {
var adjustIndex = this.target-this.index_start+this.real_count;
adjustIndex %= this.real_count;
adjustIndex++;
$(this.options['seemore']).innerHTML = 
"<span><b>" + adjustIndex + "</b> / " + this.real_count + "</span>";
}
},
timer: function ()
{
if( this.coords.length == 0 ) return;
if( this.coords.length > this.move_complete_count ) {
this.coords.pop();
this.coords.pop();
}
pos = this.coords.pop();
this.innerDiv.style.left = pos;
},
lazy_timer: function ()
{
d = new Date;
},
build: function ( images, startIndex, real_count )
{
if( real_count == undefined ) { real_count = images.length; }
if( !this.image_onclick ) { alert("No image onclick callback"); return; }
this.images = images;
this.real_count = real_count;
this.index_start = this.target = startIndex;
this.index_begin = -this.view_count;
this.index_end   = this.images.length + this.view_count;
this.img_refs = new Array();
this.outerDiv = $(document.createElement("div"));
this.outerDiv.makePositioned();
this.outerDiv.style.width=this.view_count*this.imageframe_width+this.imageframe_width_unit;
this.outerDiv.style.height=this.imageframe_height+this.imageframe_height_unit;
this.outerDiv.style.position='absolute';
this.outerDiv.makeClipping();
this.innerDiv = $(document.createElement("div"));
this.innerDiv.style.width=(this.imageframe_width*(images.length+2*this.view_count))+this.imageframe_width_unit;
this.innerDiv.style.height=this.imageframe_height+this.imageframe_height_unit;
this.pane.immediateDescendants().map(Element.remove);
for( var i=this.index_begin; i<this.index_end; i++ ) {
var atag = $(document.createElement("a"));
atag.img_index = i;
atag.style.border = 0;
var img = $(document.createElement("img"));
img.img_index = i;
this.img_refs[i] = img;
img.setStyle( this.image_style );
img.src = default_icon;
if( startIndex != undefined && startIndex == (i+images.length)%images.length ) {
img.birth = true;
img.src = images[(i+images.length)%images.length];
} else {
img.birth = false;
img.img_src = images[(i+images.length)%images.length];
}
if( real_count > 0 ) {
atag.href = "#";
Event.observe( atag, 'click', this.image_onclick.bindAsEventListener(this) );
}
this.innerDiv.appendChild( atag );
atag.appendChild( img );
img.style.position = "absolute";
img.style.left = (i*this.imageframe_width) + this.imageframe_width_unit;
} 
this.outerDiv.appendChild( this.innerDiv );
this.pane.appendChild( this.outerDiv );
if( images.length < 2 ) {
var dimmed = {'color':'rgb(210,222,237)'};
this.prev.setStyle(dimmed);
this.next.setStyle(dimmed);
if( this.seemore ) {
this.seemore.setStyle(dimmed);
}
this.prev.alt = '';
this.next.alt = '';
Event.observe( this.prev, 'click', function(e){Event.stop(e);} );
Event.observe( this.next, 'click', function(e){Event.stop(e);} );
} else {
if( !this.options.is_large && this.prev.descendants()[0].tagName == 'IMG') {
this.prev.descendants()[0].src = '/img/ico/ico_idcard_pre.gif';
}
if( !this.options.is_large && this.next.descendants()[0].tagName == 'IMG') {
this.next.descendants()[0].src = '/img/ico/ico_idcard_next.gif';
}
Event.observe( this.prev, 'click', this.onclick_prev.bindAsEventListener(this) );
Event.observe( this.next, 'click', this.onclick_next.bindAsEventListener(this) );
}
if( this.arrowsbar ) {
}
if( this.close ) {
Event.observe( this.close, 'click', this.onclick_close.bindAsEventListener(this) );
}
this.update_seemore();
},
run: function (target)
{
this.target = target;
this.innerDiv.style.position = "absolute";
this.innerDiv.style.left=this.real_coord(this.target);
if( this.timer_handle ) {
this.timer_handle.stop();
}
this.load_images();
this.frame.show();
this.timer_handle = new PeriodicalExecuter( this.timer.bind(this), this.freq );
},
stop: function()
{
if( !this.timer_handle ) return;
this.timer_handle.stop();
},
set_image_click: function( callback )
{
this.image_onclick = callback;
},
hide: function()
{
this.stop();
this.frame.hide();
idtail_hide_gray_screen();
},
show: function(pn)
{
this.run( pn.target );
}
} );
function idtail_show_large(username, pane, img_index)
{
var seq = pane.options.seq;
gs = idtail_add_gray_screen();
idtail_show_gray_screen();
if( pane.large_pane == undefined ) {
var options = {
is_large: true,
seq: pane.options.seq,
pane:'idtail_largephotonav'+seq,
close:'idtail_large_close'+seq,
prev:'idtail_large_prev'+seq,
next:'idtail_large_next'+seq,
border:'none',
image_width:'500px',
image_height:'500px',
image_padding: '0',
imageframe_width:'500px',
imageframe_height:'500px' };
options.frame = idtail_draw_lightbox(options);
pane.large_pane = new IDtailPhotoNav(options, 'large pane');
pane.large_pane.set_image_click( function(e) {pane.large_pane.hide(); Event.stop(e);} );
pane.large_pane.build( pane.large_images );
IDtailPhotoNav.large_panes.push( pane.large_pane );
}
var w = window;
window_width = (w.document.documentElement.offsetWidth  || w.document.body.clientWidth);
Position.prepare();
pane.large_pane.options.frame.style.left = 
( window_width - idtail_get_px(pane.large_pane.options.imageframe_width))/2+ "px";
pane.large_pane.options.frame.style.top = 
(Position.deltaY + 150)+"px";
pane.large_pane.run( img_index );
}
function idtail_get_px( length )
{
return parseInt( length );
}
function idtail_draw_lightbox(options)
{
var seq = options.seq;
var idtail_lightbox = $(document.createElement("div"));
idtail_lightbox.style.zIndex = 99;
idtail_lightbox.innerHTML = 
'<div style="position:relative; float:left; height:545px;width:500px; border:solid 1px #4b4b4b; padding:6px; background:url('+idtail_base_url+'/img/bg/bg_photo_layer.gif) repeat-x bottom #fff" id="idtail_lightbox'+seq+'"><div href="#" style="position:relative" id="idtail_largephotonav'+seq+'"></div><div style="position:absolute; width: 500px; bottom:14px" id="idtail_large_arrowsbar'+seq+'" style="text-align:center; display:relative; width:'+options['imageframe_width']+'; padding:12px 0 8px 0"><div style="position:absolute; margin-left:auto; margin-right:auto; left:230px; bottom:0px;"><a href="#" id="idtail_large_prev'+seq+'"><img style="border:none" src="'+idtail_base_url+'/img/ico/ico_pre2.gif" alt="" /></a> <a href="#" id="idtail_large_next'+seq+'"><img style="border:none" src="'+idtail_base_url+'/img/ico/ico_next2.gif" alt="" /></a></div><a href="#" id="idtail_large_close'+seq+'" style="position:absolute; bottom:0px; right:6px"><img style="border:none" src="'+idtail_base_url+'/img/ico/ico_close_l.gif" alt="" /></a></div></div>';
document.body.appendChild( idtail_lightbox );
Position.absolutize(idtail_lightbox);
return idtail_lightbox;
}
function idtail_photo(username, options, init_img_url, json )
{
var nav_seq = IDtailPhotoNav.nav_seq;
if( init_img_url == undefined ) init_img_url = '';
if( options == undefined || options == '' ) options = new Array();
if( !options['see_more']          ) options['see_more'] = 'More..';
if( !options['prev']              ) options['prev'] = 'Prev';
if( !options['next']              ) options['next'] = 'Next';
if( !options['view_count']        ) options['view_count'] = 1;
if( !options['image_width']       ) options['image_width']  = '160px';
if( !options['image_height']      ) options['image_height'] = '160px';
if( !options['image_padding']     ) options['image_padding'] = '0';
if( !options['imageframe_width']  ) options['imageframe_width']  = '160px';
if( !options['imageframe_height'] ) options['imageframe_height'] = '160px';
options['image_style'] = "style='"+
"border:none;"+
"padding:"+options['image_padding']+";"+
"width:"+options['image_width']+";"+
"height:"+options['image_height']+"'";
imageframe_width = (parseFloat( options['imageframe_width'] ) * options['view_count']) +
options.imageframe_width.substr(options.imageframe_width.length-2);
imageframe_height = options['imageframe_height'];
var html_photo_navis =  '<div class="photo_more">'+
'<div id="idtail_photo_arrowsbar'+nav_seq+'">'+
'<a href="#" id="idtail_photo_prev'+nav_seq+'"><img src="/img/ico/ico_idcard_pre_off.gif" alt="이전" /></a>'+
'<span id="idtail_photo_seemore'+nav_seq+'"></span>'+
'<a href="#" id="idtail_photo_next'+nav_seq+'"><img src="/img/ico/ico_idcard_next_off.gif" alt="다음" /></a>' +
'</div>'+
'</div>';
var html_photo_pane = '<div id="idtail_photopane'+nav_seq+'">'+
'<div href="#" style="float:left; position:relative; border:0px;width:'+imageframe_width+'; height:'+imageframe_height+'" id="idtail_photonav'+nav_seq+'">'+
'<img class="photo_idcard" '+options['image_style']+' src="'+init_img_url+'" />'+
'</div>'+
'</div>';
document.write(html_photo_navis + html_photo_pane);
options['seq'] = nav_seq;
options['frame'] = $('idtail_photopane'+nav_seq);
options['pane'] = 'idtail_photonav'+nav_seq;
options['seemore'] = 'idtail_photo_seemore'+nav_seq;
options['prev'] = 'idtail_photo_prev'+nav_seq;
options['next'] = 'idtail_photo_next'+nav_seq;
options['is_large'] = false;
options['border'] = 'solid 1px #e9a933';
IDtailPhotoNav.nav_seq++;
var image_pane = new IDtailPhotoNav(options, 'Thumbnail pane');
IDtailPhotoNav.image_panes.push( image_pane );
image_pane.set_image_click( function(e) {
var el = Event.element(e);
idtail_show_large(username,image_pane, el.img_index); Event.stop(e);} );
if( json == undefined ) {
var fetch_url = "/images/ajax_list/" + username + "/160x160/500x500";
new Ajax.Request( fetch_url, { 
'onComplete': function(transport, json) {
image_pane.large_images = json.images;
image_pane.build(json.thumbs,json.start,json.real_count);
image_pane.run(json.start);
},
'onException': function(a,b) { try{console.error( a + " " + b );} catch(e){} }
} );
} else {
image_pane.large_images = json.images;
image_pane.build(json.thumbs,json.start,json.real_count);
image_pane.run(json.start);
}
}
}
if( window.IDtailPhotoNav.nav_seq == undefined ) {
IDtailPhotoNav.nav_seq = 0;
IDtailPhotoNav.image_panes = new Array();
IDtailPhotoNav.large_panes = new Array();
}
infoDisplay = -1;
window.set_focus_disabled = true;
function toggleinfo()
{
if( infoDisplay == -1 ) {
infoDisplay = $('mydtail_info').visible() ? 1 : 0;
}
if( infoDisplay ) {
$('mydtail_info').hide();
} else {
$('mydtail_info').show();
}
infoDisplay = 1 - infoDisplay;
}
function flash_on_request_network()
{
var URL = "/network/ajax_get_sendable_code/";
new Ajax.Request(URL, {  
onSuccess: function(xmlHttp)
{
onCompleteRequestNetwork(xmlHttp.responseText, null);
}
});
}
function flash_on_note_send()
{
var returnUrl = encodeURIComponent(window.location);
lightbox('/notes/send_with_url?returnUrl=' + returnUrl, {width:380, height:300, top:420, left:130, position:'absolute'});
}
function refresh_rss(id)
{
show_ajax_hour_glasss( _("Refreshing RSS...") );
new Ajax.Request( '/rssitem/ajax_refresh/'+id, { 
'method' : 'post',
'postBody' : '',
'onSuccess': function(t,json_obj) 
{
new Ajax.Updater( $('mydtailinfo'), '/mydtail/ajax_index/mydtailinfo', {} );
setTimeout( hide_ajax_hour_glasss, 1000 );
},
'onFailure': function(t)
{
show_ajax_hour_glasss( _("Refresh failed") );
setTimeout( hide_ajax_hour_glasss, 5000 );
},
'onException': function(t,e)
{
}
});
return false;
}
function acl_help()
{
lightbox( '/mydtail/ajax_acl_help', {
height: 350,
width: 420,
top: 200,
position: 'absolute',
overflow: 'hidden'
}
);
}
function acl_set(index)
{
lightbox( '/mydtail/ajax_acl_set/' + index, {
height: 350,
width: 390,
top: 200,
position: 'absolute',
'overflowX': 'none',
'overflowY': 'auto',
onComplete: function() { 
$('acl_set_form').original_values = Form.serialize($('acl_set_form'));
Event.observe( $('acl_set_form'), "submit", acl_set_form_sumit );
if( $('open_to_all').checked || $('hide').checked ) { select_all_groups( false ); }
}
}
);
}
function acl_set_form_sumit(e)
{
if( !$('network_only').checked ) {
hideLightbox();
return update_form_onsubmit(e);
}
var chks = document.getElementsByTagName('input');
var ok = false;
for( var i=0; i<chks.length; i++ ) {
if( chks[i].className.indexOf('group_sel') <0 ) {
continue;
}
if( chks[i].checked ) ok = true;
}
if( ok ) {
hideLightbox();
return update_form_onsubmit(e);
}
if( confirm( _("You chose to show your information only to your network\nBut no group is checked, are you sure?")) ) {
hideLightbox();
return update_form_onsubmit(e);
}
Event.stop(e);
return false;
}
function select_all_groups( default_value ) {
var chks = document.getElementsByTagName('input');
var select_all_value = false;
var disabled;
if( default_value != undefined ) {
select_all_value = default_value;
disabled = !select_all_value;
document.getElementById('select_all').checked = default_value;
document.getElementById('select_all').disabled = disabled;
} else {
disabled = false;
select_all_value = document.getElementById('select_all').checked;
}
for( var i=0; i<chks.length; i++ ) {
if( chks[i].className.indexOf('group_sel') <0 ) {
continue;
}
chks[i].checked = select_all_value;
chks[i].disabled = disabled;
}
}
function update_select_all()
{
var chks = document.getElementsByTagName('input');
var select_all_value = true;
for( var i=0; i<chks.length; i++ ) {
if( chks[i].className.indexOf('group_sel') <0 ) {
continue;
}
if( !chks[i].checked ) select_all_value = false;
}
document.getElementById('select_all').checked = select_all_value;
}
function page_onload()
{
}
var default_guestbook_msg = _("Leave your message to send(upto 1000 chars.)");
function updatePage(target, url)
{
new Ajax.Updater(target, url, {method:'get'});
}
function checkGuestbookSubmit(form_id)
{
theForm = $("guestbook_form_" + form_id);
textObj = $("guestbook_textarea_" + form_id);
text = textObj.value;
if( text == default_guestbook_msg || text == "" )
{
alert(_("please fill in a blank"));
textObj.select();
return;
}
if( text.length > 1000 )
{
alert(_("you can't put the message which over 2000bytes"));
textObj.focus();
return;
}
theForm.submit();
}
function clearTextarea(obj)
{
if(obj.value == default_guestbook_msg)
{
obj.value = '';
}
}
function toggleReply(guest_id)
{
obj = document.getElementById("guestbook_reply_" + guest_id);
if( obj.style.display == 'none' )
{
obj.style.display = "";
var htm =obj.parentNode.innerHTML;
obj.className = "re";
obj.parentNode.innerHTML =htm;
$("guestbook_textarea_" + guest_id).select();
}
else
{
obj.style.display = 'none';
var htm =obj.parentNode.innerHTML;
obj.className = "re";
obj.parentNode.innerHTML =htm; 
}
}
function submitReply()
{
if(!form || form["body"].value.strop().length == 0)
{
return;
}
var onSuccess = function(t) {
var json;
try {
json = eval("(" + t.responseText + ")");
} catch(e) {
activityIndicator.hide();
alert(e + "\n" + t.responseText)
errFunc(t);
return;
}
if (!(json.result)) {
activityIndicator.hide();
notification_message.show_message("댓글을 작성하지 못했습니다. " + json.return_value);
return;
}
notification_message.show_message("댓글을 작성했습니다.");
postID = form["post_id"].value;
activityIndicator.hide(); 
}
var onFail = function(t) {
activityIndicator.hide();
alert("댓글을 작성하지 못했습니다. " + t.status);
}
var params = Form.serialize(form);
new Ajax.Request(form.action, {
asynchronous: true,
parameters: params, 
onSuccess: onSuccess, 
onFailure: onFail
});
var activityIndicator = new ActivityIndicator(form, form["commit"]);
activityIndicator.show();
}
function onClickNewEntry(textarea)
{
if( undefined == textarea.firstclick ) {
textarea.defaultValue = textarea.value;
textarea.value = '';
}
textarea.firstclick = true;
}
function submitSingleNote()
{
}
function sendSMS(form)
{
form = $(form);
try {
document.getElementById('sms').value = 1;
} catch(e) {}
$(form).submit();
}
function onGroupNoteSubmit(type)
{
obj = $("note_selected_userlist");
var cnt = obj.options.length;
for (var i=0; i < cnt; i++)
{
obj.options[i].selected = true;
}
if( type == 'sms' ) {
try {
document.getElementById('sms').value = 1;
} catch(e) {}
}
document.groupsend.submit();
}	
function onChangeGroupComboBox(group_id)
{
var URL = "/groups/ajax_request_users_of_group/" + group_id;
new Ajax.Request(URL, {  
onSuccess: function(xmlHttp)
{
onCompleteRecvUsersOfGroup(xmlHttp.responseText);
}
});
}
function onCompleteRecvUsersOfGroup(userObj)
{
var userList = eval(userObj);
selectBox = $("note_group_userlist");
var cnt = selectBox.options.length;
for (var i=0; i < cnt; i++)
{
selectBox.options[0].remove();
}
for (i=0; i < userList.length; i++)
{
addOption(selectBox, userList[i].fullname, userList[i].id);
}
}
var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);
function addOption(theSel, theText, theValue)
{
var newOpt = new Option(theText, theValue);
var selLength = theSel.length;
theSel.options[selLength] = newOpt;
}
function deleteOption(theSel, theIndex)
{ 
var selLength = theSel.length;
if(selLength>0)
{
theSel.options[theIndex] = null;
}
}
function moveOptions(theSelFrom, theSelTo)
{
var selLength = theSelFrom.length;
var selectedText = new Array();
var selectedValues = new Array();
var selectedCount = 0;
var i;
for(i=selLength-1; i>=0; i--)
{
if(theSelFrom.options[i].selected)
{
selectedText[selectedCount] = theSelFrom.options[i].text;
selectedValues[selectedCount] = theSelFrom.options[i].value;
deleteOption(theSelFrom, i);
selectedCount++;
}
}
for(i=selectedCount-1; i>=0; i--)
{
addOption(theSelTo, selectedText[i], selectedValues[i]);
}
if(NS4) history.go(0);
}
function select_notes_default_message(obj)
{
if( _('Please leave a message') == obj.value )
{
obj.select();
}
}
function notes_action_after_load()
{
if( window.set_focus_disabled ) {
return;
}
var textareas = document.getElementsByTagName("textarea");
for( var i = 0; i < textareas.length; i++ )
{
if( $(textareas[i]).value && !textareas[i].readOnly)
{
textareas[i].focus();
if( _('Please leave a message') == textareas[i].value )
{
textareas[i].select();
}
break;
}
}
}
function checkNotesDelete()
{
if( hasCheckedCheckbox('form_notes_list', 'data[Notes][id][]') == false)
{
alert(_('You should select at least one person'));
return false;
}
if(window.confirm("정말 쪽지를 삭제하시겠습니까?") == true)
{
$('form_notes_list').action = '/notes/do_delete';
$('form_notes_list').submit();
}
}
function checkNotesMarkAsRead()
{
if( hasCheckedCheckbox('form_notes_list', 'data[Notes][id][]') == false)
{
alert(_('You should select at least one person'));
return false;
}
if(window.confirm("모두 읽음표시로 변경합니까?") == true)
{
$('form_notes_list').action = '/notes/mark_as_read';
$('form_notes_list').submit();
}
}
Event.observe( window, 'load', notes_action_after_load );
var MAFET = {
click: function(e) {
li = Event.element(e);
MAFET.edit(li);
},
blur: function(e) {
var input = Event.element(e);
setTimeout( function() {
var ul = input.ul;
if( ul.current_li != input.li ) {
return;
}
MAFET.kill( input );
MAFET.update( ul );
MAFET.makeup_last_part( ul );
}, 100 );
},
update: function( ul ) {
try {
var LIs = ul.getElementsByTagName( 'li' );
} catch (e) {
LIs = { length: 0};
}
var tags = '';
for( var i=0; i<LIs.length; i++ )
{
if( !LIs[i].firstChild.data.strip() ) {
continue;
}
if( LIs[i].challenger ) {
continue;
}
if( tags ) {
tags += ',';
}
tags += LIs[i].firstChild.data;
}
if( $('mafet_input') && $('mafet_input').value ) {
if( tags ) { tags += ','; }
tags += $('mafet_input').value;
}
ul.input_element.value = tags;
setTimeout( function() {
if( ul.mafet_callbacks['update'] ) {
ul.mafet_callbacks['update'](ul,tags);
}
}, 100 );
},
add_comma: function( ul ) {
var LIs;
try {
LIs = ul.getElementsByTagName( 'li' );
} catch (e) {
return;
}
if( LIs.length <= 0 || LIs[LIs.length-1].comma ) {
return;
}
comma = document.createTextNode( ',' );
LIs[ LIs.length - 1].comma = comma;
ul.appendChild( comma );
},
makeup_last_part: function( ul ) {
var LIs;
try {
LIs = ul.getElementsByTagName( 'li' );
} catch (e) {
LIs = { length: 0 };
}
if( LIs.length <= 0 ) {
if( ul.unreg_msg ) {
li = MAFET.append_li_tag( ul, ul.unreg_msg );
li.challenger = true;
return;
}
}
if( !ul.unreg_msg ) {
MAFET.ready_to_edit( ul );
}
if( LIs.length > 0 && LIs[LIs.length-1].comma ) {
ul.removeChild( LIs[LIs.length-1].comma );
LIs[LIs.length-1].comma = null;
}
},
ready_to_edit: function( ul ) {
if( ul.current_li ) {
return null;
}
var li = MAFET.append_li_tag( ul, '', true );
MAFET.editable( li );
return li;
},
append_li_tag: function(ul, tag, forcely) {
if( !forcely && !tag.strip() ) {
return null;
}
if( ul.childNodes.length > 0 ) {
MAFET.add_comma( ul );
}
var li = document.createElement( 'li' );
Element.extend(li);
li.appendChild( document.createTextNode(tag) );
ul.appendChild( li );
if( ul.mafet_styles['li'] ) { $(li).setStyle( ul.mafet_styles['li'] ); }
if( ul.mafet_classes['li'] ) { li.className = ul.mafet_classes['li']; }
Event.observe( li, 'click', MAFET.click );
return li;
},
keypress: function(e) {
var input = Event.element(e);
keyCode = e.keyCode;
if( e.shiftKey && keyCode == 9 ) keyCode = -1;
if( e.charCode == 44 ) keyCode = 9;
switch(keyCode) {
case -1:
Event.stop(e);
MAFET.shift_prev(input);
break;
case 8:
if( input.value == '' ) {
MAFET.shift_prev(input);
Event.stop(e);
}
break;
case 9:
case 44:
Event.stop(e);
if( input.value != '' ) {
MAFET.shift_next(input);
}
break;
case 13:
input.blur(e);
MAFET.shift_next(input);
break;
default:
break;
}
},
shift_prev: function(element) {
Element.extend( element.li );
prev = element.li.previous('li');
if( prev ) {
MAFET.kill( element );
MAFET.update( element.ul );
MAFET.edit( prev );
} else {
MAFET.update( element.ul );
}
},
shift_next: function(element) {
Element.extend( element.li );
next = element.li.next('li');
if( next ) {
MAFET.kill( element );
MAFET.update( element.ul );
MAFET.edit( next );
} else if( element.value.strip() ) {
next = MAFET.append_li_tag( element.ul, '', true );
MAFET.kill( element );
MAFET.update( element.ul );
MAFET.edit( next );
}
},
kill: function(input) {
input=$(input);
if( !input ) {
return;
}
input.ul.current_li = null;
input.timer.stop();
if( !input.value.strip() ) {
if( input.li.comma ) {
input.parentNode.removeChild( input.li.comma );
}
input.parentNode.removeChild( input.li );
} else {
input.li.firstChild.data =input.value; 
input.li.show();
}
input.parentNode.removeChild( input );
},
inputcheck: function(PE) {
input = PE.input;
if( input.value.substr( input.value.length-1) == ',' ) {
if( input.value != '' ) {
input.value = input.value.substr( 0, input.value.length-1 );
MAFET.shift_next(input);
}
}
},
editable: function(li) {
var input = document.createElement( "input" );
input.id = "mafet_input";
input.type = "text";
input.li = li;
input.ul = li.parentNode;
if( !li.challenger ) {
input.value = li.firstChild.data;
}
input.timer = new PeriodicalExecuter( MAFET.inputcheck.bind(input), 0.1 );
input.timer.input = input;
li.challenger = false;
li.parentNode.insertBefore( input, li.nextSibling );
li.parentNode.current_li = li;
Event.observe( input, 'keypress', MAFET.keypress );
Event.observe( input, 'blur', MAFET.blur );
return input;
},
edit: function(li) {
$(li).hide();
if( li.parentNode.current_li ) {
MAFET.kill( $('mafet_input') );
MAFET.update( li.parentNode );
li.parentNode.current_li = null;
}
input = MAFET.editable(li);
MAFET.makeup_last_part( li.parentNode );
input.focus();
input.select();
}
};
function make_as_fancy_editable_tag( element, input_element, styles, classes, callbacks, unreg_msg )
{
element = $(element);
inp = $(input_element);
if( inp.fancy_enabled == undefined ) {
inp.fancy_enabled = true;
} else {
return;
}
if( !element || !input_element ) {
return;
}
element.hide();
inp.hide();
if( styles    == undefined ) styles = {};
if( classes   == undefined ) classes = {};
if( callbacks == undefined ) callbacks = {};
var tags = inp.value.split( "," );
var ul = document.createElement( 'ul' );
Element.extend(ul);
if( styles.ul ) { ul.setStyle(styles.ul); }
if( classes.ul ) { ul.className = classes.ul; }
ul.mafet_styles = styles;
ul.mafet_classes = classes;
ul.mafet_callbacks = callbacks;
ul.unreg_msg = unreg_msg;
element.parentNode.insertBefore( ul, inp );
ul.input_element = inp;
ul.current_li = null;
for( var i=0; i<tags.length;i++ ) {
MAFET.append_li_tag( ul, tags[i] );
}
MAFET.makeup_last_part( ul );
}
if(typeof(Control) == "undefined")
Control = {};
Control.Modal = Class.create();
Object.extend(Control.Modal,{
loaded: false,
loading: false,
loadingTimeout: false,
overlay: false,
container: false,
current: false,
ie: false,
effects: {
containerFade: false,
containerAppear: false,
overlayFade: false,
overlayAppear: false
},
targetRegexp: /#(.+)$/,
imgRegexp: /\.(jpe?g|gif|png|tiff?)$/i,
overlayStyles: {
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%',
zIndex: 9998
},
overlayIEStyles: {
position: 'absolute',
top: 0,
left: 0,
zIndex: 9998
},
disableHoverClose: false,
load: function(){
if(!Control.Modal.loaded){
Control.Modal.loaded = true;
Control.Modal.ie = !(typeof document.body.style.maxHeight != 'undefined');
Control.Modal.overlay = $(document.createElement('div'));
Control.Modal.overlay.id = 'modal_overlay';
Object.extend(Control.Modal.overlay.style,Control.Modal['overlay' + (Control.Modal.ie ? 'IE' : '') + 'Styles']);
Control.Modal.overlay.hide();
Control.Modal.container = $(document.createElement('div'));
Control.Modal.container.id = 'modal_container';
Control.Modal.container.hide();
Control.Modal.loading = $(document.createElement('div'));
Control.Modal.loading.id = 'modal_loading';
Control.Modal.loading.hide();
var body_tag = document.getElementsByTagName('body')[0];
body_tag.appendChild(Control.Modal.overlay);
body_tag.appendChild(Control.Modal.container);
body_tag.appendChild(Control.Modal.loading);
Control.Modal.container.observe('mouseout',function(event){
if(!Control.Modal.disableHoverClose && Control.Modal.current && Control.Modal.current.options.hover && !Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
Control.Modal.close();
});
}
},
open: function(contents,options){
options = options || {};
if(!options.contents)
options.contents = contents;
var modal_instance = new Control.Modal(false,options);
modal_instance.open();
return modal_instance;
},
close: function(force){
if(typeof(force) != 'boolean')
force = false;
if(Control.Modal.current)
Control.Modal.current.close(force);
},
attachEvents: function(){
Event.observe(window,'load',Control.Modal.load);
Event.observe(window,'unload',Event.unloadCache,false);
},
center: function(element){
if(!element._absolutized){
element.setStyle({
position: 'absolute'
}); 
element._absolutized = true;
}
var dimensions = element.getDimensions();
Position.prepare();
var offset_left = (Position.deltaX + Math.floor((Control.Modal.getWindowWidth() - dimensions.width) / 2));
var offset_top = (Position.deltaY + ((Control.Modal.getWindowHeight() > dimensions.height) ? Math.floor((Control.Modal.getWindowHeight() - dimensions.height) / 2) : 0));
element.setStyle({
top: ((dimensions.height <= Control.Modal.getDocumentHeight()) ? ((offset_top != null && offset_top > 0) ? offset_top : '0') + 'px' : 0),
left: ((dimensions.width <= Control.Modal.getDocumentWidth()) ? ((offset_left != null && offset_left > 0) ? offset_left : '0') + 'px' : 0)
});
},
getWindowWidth: function(){
return (self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0);
},
getWindowHeight: function(){
return (self.innerHeight ||  document.documentElement.clientHeight || document.body.clientHeight || 0);
},
getDocumentWidth: function(){
return Math.min(document.body.scrollWidth,Control.Modal.getWindowWidth());
},
getDocumentHeight: function(){
return Math.max(document.body.scrollHeight,Control.Modal.getWindowHeight());
},
onKeyDown: function(event){
if(event.keyCode == Event.KEY_ESC)
Control.Modal.close();
}
});
Object.extend(Control.Modal.prototype,{
mode: '',
html: false,
href: '',
element: false,
src: false,
imageLoaded: false,
ajaxRequest: false,
initialize: function(element,options){
this.element = $(element);
this.options = {
beforeOpen: Prototype.emptyFunction,
afterOpen: Prototype.emptyFunction,
beforeClose: Prototype.emptyFunction,
afterClose: Prototype.emptyFunction,
onSuccess: Prototype.emptyFunction,
onFailure: Prototype.emptyFunction,
onException: Prototype.emptyFunction,
beforeImageLoad: Prototype.emptyFunction,
afterImageLoad: Prototype.emptyFunction,
autoOpenIfLinked: true,
contents: false,
loading: false, //display loading indicator
fade: false,
fadeDuration: 0.75,
image: false,
imageCloseOnClick: true,
hover: false,
iframe: false,
iframeTemplate: new Template('<iframe src="#{href}" width="100%" height="100%" frameborder="0" scrolling="no" id="#{id}"></iframe>'),
evalScripts: true, //for Ajax, define here instead of in requestOptions
requestOptions: {}, //for Ajax.Request
overlayDisplay: true,
overlayClassName: '',
overlayCloseOnClick: true,
containerClassName: '',
opacity: 0.3,
zIndex: 9998,
width: null,
height: null,
offsetLeft: 0, //for use with 'relative'
offsetTop: 0, //for use with 'relative'
position: 'absolute' //'absolute' or 'relative'
};
Object.extend(this.options,options || {});
var target_match = false;
var image_match = false;
if(this.element){
target_match = Control.Modal.targetRegexp.exec(this.element.href);
image_match = Control.Modal.imgRegexp.exec(this.element.href);
}
if(this.options.position == 'mouse')
this.options.hover = true;
if(this.options.contents){
this.mode = 'contents';
}else if(this.options.image || image_match){
this.mode = 'image';
this.src = this.element.href;
}else if(target_match){
this.mode = 'named';
var x = $(target_match[1]);
this.html = x.innerHTML;
x.remove();
this.href = target_match[1];
}else{
this.mode = (this.options.iframe) ? 'iframe' : 'ajax';
this.href = this.element.href;
}
if(this.element){
if(this.options.hover){
this.element.observe('mouseover',this.open.bind(this));
this.element.observe('mouseout',function(event){
if(!Position.within(Control.Modal.container,Event.pointerX(event),Event.pointerY(event)))
this.close();
}.bindAsEventListener(this));
}else{
this.element.onclick = function(event){
this.open();
Event.stop(event);
return false;
}.bindAsEventListener(this);
}
}
var targets = Control.Modal.targetRegexp.exec(window.location);
this.position = function(event){
if(this.options.position == 'absolute')
Control.Modal.center(Control.Modal.container);
else{
var xy = (event && this.options.position == 'mouse' ? [Event.pointerX(event),Event.pointerY(event)] : Position.cumulativeOffset(this.element));
Control.Modal.container.setStyle({
position: 'absolute',
top: xy[1] + (typeof(this.options.offsetTop) == 'function' ? this.options.offsetTop() : this.options.offsetTop) +(20) + 'px',
left: xy[0] + (typeof(this.options.offsetLeft) == 'function' ? this.options.offsetLeft() : this.options.offsetLeft) + 'px'
});
}
if(Control.Modal.ie){
Control.Modal.overlay.setStyle({
height: Control.Modal.getDocumentHeight() + 'px',
width: Control.Modal.getDocumentWidth() + 'px'
});
}
}.bind(this);
if(this.mode == 'named' && this.options.autoOpenIfLinked && targets && targets[1] && targets[1] == this.href)
this.open();
},
showLoadingIndicator: function(){
if(this.options.loading){
Control.Modal.loadingTimeout = window.setTimeout(function(){
var modal_image = $('modal_image');
if(modal_image)
modal_image.hide();
Control.Modal.loading.style.zIndex = this.options.zIndex + 1;
Control.Modal.loading.update('<img id="modal_loading" src="' + this.options.loading + '"/>');
Control.Modal.loading.show();
Control.Modal.center(Control.Modal.loading);
}.bind(this),250);
}
},
hideLoadingIndicator: function(){
if(this.options.loading){
if(Control.Modal.loadingTimeout)
window.clearTimeout(Control.Modal.loadingTimeout);
var modal_image = $('modal_image');
if(modal_image)
modal_image.show();
Control.Modal.loading.hide();
}
},
open: function(force){
if(!force && this.notify('beforeOpen') === false)
return;
if(!Control.Modal.loaded)
Control.Modal.load();
Control.Modal.close();
if(!this.options.hover)
Event.observe($(document.getElementsByTagName('body')[0]),'keydown',Control.Modal.onKeyDown);
Control.Modal.current = this;
if(!this.options.hover)
Control.Modal.overlay.setStyle({
zIndex: this.options.zIndex,
opacity: this.options.opacity
});
Control.Modal.container.setStyle({
zIndex: this.options.zIndex + 1,
width: (this.options.width ? (typeof(this.options.width) == 'function' ? this.options.width() : this.options.width) + 'px' : null),
height: (this.options.height ? (typeof(this.options.height) == 'function' ? this.options.height() : this.options.height) + 'px' : null)
});
if(Control.Modal.ie && !this.options.hover){
$A(document.getElementsByTagName('select')).each(function(select){
select.style.visibility = 'hidden';
});
}
Control.Modal.overlay.addClassName(this.options.overlayClassName);
Control.Modal.container.addClassName(this.options.containerClassName);
switch(this.mode){
case 'image':
this.imageLoaded = false;
this.notify('beforeImageLoad');
this.showLoadingIndicator();
var img = document.createElement('img');
img.onload = function(img){
this.hideLoadingIndicator();
this.update([img]);
if(this.options.imageCloseOnClick)
$(img).observe('click',Control.Modal.close);
this.position();
this.notify('afterImageLoad');
img.onload = null;
}.bind(this,img);
img.src = this.src;
img.id = 'modal_image';
break;
case 'ajax':
this.notify('beforeLoad');
var options = {
method: 'post',
onSuccess: function(request){
this.hideLoadingIndicator();
this.update(request.responseText);
this.notify('onSuccess',request);
this.ajaxRequest = false;
}.bind(this),
onFailure: function(){
this.notify('onFailure');
}.bind(this),
onException: function(){
this.notify('onException');
}.bind(this)
};
Object.extend(options,this.options.requestOptions);
this.showLoadingIndicator();
this.ajaxRequest = new Ajax.Request(this.href,options);
break;
case 'iframe':
this.update(this.options.iframeTemplate.evaluate({href: this.href, id: 'modal_iframe'}));
break;
case 'contents':
this.update((typeof(this.options.contents) == 'function' ? this.options.contents() : this.options.contents));
break;
case 'named':
this.update(this.html);
break;
}
if(!this.options.hover){
if(this.options.overlayCloseOnClick && this.options.overlayDisplay)
Control.Modal.overlay.observe('click',Control.Modal.close);
if(this.options.overlayDisplay){
if(this.options.fade){
if(Control.Modal.effects.overlayFade)
Control.Modal.effects.overlayFade.cancel();
try{
Control.Modal.effects.overlayAppear = new Effect.Appear(Control.Modal.overlay,{
queue: {
position: 'front',
scope: 'Control.Modal'
},
to: this.options.opacity,
duration: this.options.fadeDuration / 2000
});
}catch(e){
}
}else
Control.Modal.overlay.show();
}
}
if(this.options.position == 'mouse'){
this.mouseHoverListener = this.position.bindAsEventListener(this);
this.element.observe('mousemove',this.mouseHoverListener);
}
this.notify('afterOpen');
},
update: function(html){
if(typeof(html) == 'string')
Control.Modal.container.update(html);
else{
Control.Modal.container.update('');
(html.each) ? html.each(function(node){
Control.Modal.container.appendChild(node);
}) : Control.Modal.container.appendChild(node);
}
if(this.options.fade){
if(Control.Modal.effects.containerFade)
Control.Modal.effects.containerFade.cancel();
Control.Modal.container.show();
try{
Control.Modal.effects.containerAppear = new Effect.Appear(Control.Modal.container,{
queue: {
position: 'end',
scope: 'Control.Modal'
},
to: 1,
duration: this.options.fadeDuration /2000
});
}catch(e){
}
}else
Control.Modal.container.show();
this.position();
Event.observe(window,'resize',this.position,false);
Event.observe(window,'scroll',this.position,false);
},
close: function(force){
if(!force && this.notify('beforeClose') === false)
return;
if(this.ajaxRequest)
this.ajaxRequest.transport.abort();
this.hideLoadingIndicator();	
if(this.mode == 'image'){
var modal_image = $('modal_image');
if(this.options.imageCloseOnClick && modal_image)
modal_image.stopObserving('click',Control.Modal.close);
}
if(Control.Modal.ie && !this.options.hover){
$A(document.getElementsByTagName('select')).each(function(select){
select.style.visibility = 'visible';
});			
}
if(!this.options.hover)
Event.stopObserving(window,'keyup',Control.Modal.onKeyDown);
Control.Modal.current = false;
Event.stopObserving(window,'resize',this.position,false);
Event.stopObserving(window,'scroll',this.position,false);
if(!this.options.hover){
if(this.options.overlayCloseOnClick && this.options.overlayDisplay)
Control.Modal.overlay.stopObserving('click',Control.Modal.close);
if(this.options.overlayDisplay){
if(this.options.fade){
if(Control.Modal.effects.overlayAppear)
Control.Modal.effects.overlayAppear.cancel();
Control.Modal.overlay.hide();
}else
Control.Modal.overlay.hide();
}
}
if(this.options.fade){
if(Control.Modal.effects.containerAppear)
Control.Modal.effects.containerAppear.cancel();
Control.Modal.effects.containerFade = new Effect.SwitchOff(Control.Modal.container,{
duration: this.options.fadeDuration / 100
});
}else{
Control.Modal.container.hide();
Control.Modal.container.update('');
this.resetClassNameAndStyles();
}
if(this.options.position == 'mouse')
this.element.stopObserving('mousemove',this.mouseHoverListener);
this.notify('afterClose');
},
resetClassNameAndStyles: function(){
Control.Modal.overlay.removeClassName(this.options.overlayClassName);
Control.Modal.container.removeClassName(this.options.containerClassName);
Control.Modal.container.setStyle({
height: null,
width: null,
top: null,
left: null
});
},
notify: function(event_name){
try{
if(this.options[event_name])
return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
}catch(e){
if(e != $break)
throw e;
else
return false;
}
}
});
if(typeof(Object.Event) != 'undefined')
Object.Event.extend(Control.Modal);
Control.Modal.attachEvents();
Effect.SwitchOff = function(element) {
element = $(element);
element.setStyle({opacity: 1});
var oldOpacity = 0;
return new Effect.Appear(element, Object.extend({
duration: 0.4,
from: 0,
transition: Effect.Transitions.flicker,
afterFinishInternal: function(effect) {
new Effect.Scale(effect.element, 1, { 
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) { 
effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
}
}, arguments[1] || { }));
};
Effect.Appear = function(element) {
element = $(element);
var options = Object.extend({
from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
to:   1.0,
afterFinishInternal: function(effect) {
},
beforeSetup: function(effect) {
effect.element.setOpacity(effect.options.from).show(); 
}}, arguments[1] || { });
return new Effect.Opacity(element,options);
};
var g_share_app_result = false;
function resizeFrame(mid, height)
{
var newHeight = defaultHeight;
try{
if(height && typeof height == "object"){
newHeight = height.document.body.scrollHeight;
}else{
newHeight = height;
}
}catch(e){
newHeight = defaultHeight;
}finally{
if(newHeight < 100){
newHeight = defaultHeight;
}
document.getElementById(mid).style.height = newHeight + 'px';
}
}
function setTitle(mid, title)
{
try{
$("h2", "#module_" + mid).text(title);
}catch(e){
}
}
function resize_iframe(height)
{
try{
$(this.f).style.height = (height+20) + 'px';
} catch(e) {}
}
function get_view_height(document)
{
document = document || window.document;
var vh = getViewportDimensions(document).height;
var body = document.body;
var docEl = document.documentElement;
if (document.compatMode == 'CSS1Compat' && docEl.scrollHeight) {
newHeight = docEl.scrollHeight != vh ?
docEl.scrollHeight : docEl.offsetHeight;
} else {
var sh = docEl.scrollHeight;
var oh = docEl.offsetHeight;
if (docEl.clientHeight != oh) {
sh = body.scrollHeight;
oh = body.offsetHeight;
}
if (sh > vh) {
newHeight = sh > oh ? sh : oh;
} else {
newHeight = sh < oh ? sh : oh;
}
}
return newHeight;
}
function getViewportDimensions(document) {
document = document || window.document;
var x,y;
if (self.innerHeight) {
x = self.innerWidth;
y = self.innerHeight;
} else if (document.documentElement &&
document.documentElement.clientHeight) {
x = document.documentElement.clientWidth;
y = document.documentElement.clientHeight;
} else if (document.body) {
x = document.body.clientWidth;
y = document.body.clientHeight;
} else {
x = 0;
y = 0;
}
return {width: x, height: y};
};
function set_title(title)
{
try{
$$("h2", "#module_" + this.f).each( function() { this.innerHTML = title; } );
}catch(e){
}
}
function requestRemove(tab_id, app_id)
{
if(!confirm('정말 이 어플리케이션을 삭제 하시겠습니까?')){
return false;
}
var urlReq = _OPENID_HOST +'/play/old_ajax_unsubscribe?app_id='  + app_id + '&tab_id=' + tab_id;
new Json(urlReq,responseRemove);
}
function requestUpdateAppOrd(app_id, tab_id, container, ord)
{
try{
var urlReq = _OPENID_HOST + '/play/ajax_update_app_order?tab_id=' + tab_id + '&app_id=' + app_id +'&container=' + container + '&ord=' + ord;
new Json(urlReq,responseUpdateAppOrd);
}catch(e){
} 
}
function responseRemove(obj)
{
if(parseInt(obj.code) == 1){
document.location.href  = document.location.href; 
}else{
alert(obj.msg);
}
};
function responseUpdateAppOrd(){};
function responseNavigateTo(app_id, viewMode, opt_params)
{
var params = '';
try{
var supportedViews =  gadgets.views.getSupportedViews()[viewMode];
if(!supportedViews){
throw 'This is not supported views';
}
if(gadgets.views.getCurrentView().getName() == viewMode){
throw 'This viewType of gadget is already ' + viewMode;
}
if(opt_params){
if(typeof opt_params == "string"){
opt_params =  eval( '(' +  opt_params  + ')');	
}
if(opt_params && typeof opt_params == 'object'){
for(var i in opt_params){
params += i + "=" + opt_params[i] + "&";
};
}
params = params.substr(0, params.length -1);
params = base64(params);
}
}catch(e){
alert(e);
return;
}
if(supportedViews.getName() == 'canvas'){
var url = '/play/canvasframe/' + canvasParams.ownername + '/' + canvasParams.tab_id + '/'+ app_id + '?view=canvas&isOwner=' + canvasParams.isOwner;
}else{
var url = '/play/normalframe/' + normalParams.ownername + '/' + normalParams.tab_id + '?view=profile&movable=' + normalParams.isOwner;
}
if(params){
url += '&app_param_id=' + app_id + '&app_params=' + params;
}
document.location.href = url;	
return;
}
function navigateToFullPage(app_id, encoded_view_params, owner)
{
new Ajax.Request( '/play/check_install', {
method: 'post', 
encoding:'UTF-8',
postBody: 'app='+(app_id ||''),
onSuccess: function(tr) {
loadFullPage = function () {
var hostprefix = '';
if( window._IDTAIL_HOST != undefined && owner != undefined ) {
hostprefix = "http://"+owner+"."+window._IDTAIL_HOST;
}
var href = hostprefix + "/play/view#"+app_id;
if( encoded_view_params ) {
href += "&" + encoded_view_params;
}
document.location.href = href;
};
if( tr.headerJSON.code != 200 ) {
window.callbackAfterAddApp = loadFullPage;
$('app_add_link_'+app_id).onclick();
} else {
loadFullPage();
}
}
});	
}
function requestNavigateTo()
{
var viewMode = this.a[0];
if( gadgets.views.getCurrentView().getName() == viewMode ) {
return;
}
if( gadgets.views.ViewType.FULL_PAGE == viewMode ) {
app_id = this.f.replace( 'remote_iframe_', '' );
if( this.a[1] == undefined ) {
navigateToFullPage( app_id );
} else {
navigateToFullPage( 
app_id, 
gadgets.io.encodeValues( { 'view-params': encodeURIComponent( gadgets.json.stringify( this.a[1] ) ) } ),
this.a[1]['idtail_owner']
);
}
} else {
}
}
function base64(input) {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";  
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
} while (i < input.length);
return output;
}
function modalClose()
{
new Control.Modal.close();
}
function requestSuccess(app_id, type)
{
if( type == 'SHARE_APP' ) {
g_share_app_result = true;
} else if(type == 'ADD_APP'){
if( undefined != window.callbackAfterAddApp ) {
window.callbackAfterAddApp();
}
}
modalClose();
}
function removeMytem(id, callback, name)
{
var msg = '';
if( name != undefined ) {
msg = _('Do you really want to delete the application APP?');
msg = msg.replace( 'APP', name );
} else {
msg = _("Do you really want to remove the selected application(s)?");
}
if(!confirm(msg)) return false;
new Ajax.Request( '/play/ajax_remove_checked_apps', {
method: 'post', 
encoding:'UTF-8',
postBody: 'apps='+(id ||''),
onSuccess: callback || function(){}
});	
}
function requestShareApp(mid, ids, message) {
g_share_app_result = false;
var l = $('app_share_link');
if( !l ) {
l = $('app_share_link_'+mid);
if( !l ) {
try{ console.log( "No share link" ); } catch(e) {}
return;
}
}
if( l.modal !== undefined ) {
l.modal = null;
}
var rpc = this;
var rpc_callback = rpc.c;
rpc.c = null;
message = message || "";
l.href = '/play/share_app_layer/' + mid + '/' + ids.join(',') + '?msg=' + encodeURIComponent(message);
l.modal = new Control.Modal(l,
{ 
iframe:true, fade:true, width:'539px', height:'555px',
afterClose: function() { 
if (rpc_callback) {
gadgets.rpc.call(rpc.f, '__cb', null, rpc_callback, g_share_app_result ? 1:0 );
} else {
}
} 
});
l.modal.open(true);
l.href = '/play/share_app_layer/' + mid;
this.c = null;
}
