var domainFromHard="channel.aol.com";

/* Header functions*/
function loginCheck(sitedomain) {
    var sitedmn = "sitedomain="+sitedomain;
    var origPath = "" + window.location + "";
    var url="siteState="+encodeURIComponent("OrigUrl="+encodeURIComponent(origPath));
    if(_sns_isLoggedIn == true) {
        $("#userspan").text("Signed In: "+_sns_current_user);
        $("#loginlink").attr({href:"https://my.screenname.aol.com/_cqr/logout/mcLogout.psp?"+sitedmn+"&"+url, title:"Sign Out"});
        $("#loginlink").text("Sign Out");
    } else {
        $("#loginlink").attr({href:"https://my.screenname.aol.com/_cqr/login/login.psp?"+sitedmn+"&"+url, title:"Sign In"});
        $("#loginlink").text("Sign In");
    }
}
// Tog More for Search
function togMore(sShow)
{
	if (sShow == "hide")
	{
		document.getElementById("srchMoreId").style.display = "none";
	}
	else
	{
		document.getElementById("srchMoreId").style.display = "block";
	}
	return false;
}

function togFootMore(sShow)
{
	if (sShow == "hide")
	{
		document.getElementById("srchFootMoreId").style.display = "none";
	}
	else
	{
		document.getElementById("srchFootMoreId").style.display = "block";
	}
	return false;
}

// Begin : Headers 2 code
function p_o(o){return getEl(o);}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function srchSub(ref){
  var frm=p_o("search");
  var queryval = frm.topquery.value.trim();
  queryval = queryval.replace( /\+/, " ");
  newurl = ref.href + queryval;
  window.location = newurl;
  return false;
}

function searchTarget(url, newWindow, newTarget) {
    // Set the target for the form
    document.bb_topform.action = url;
    if (newWindow) {
        document.bb_topform.target = '_blank';
    } else {
        document.bb_topform.target = '';
    }
    // Update the tabs classes to allow highlighting of the selected
    var arrElements = ["search-tab-1","search-tab-2","search-tab-3","search-tab-4","search-tab-5"];
    for (var i=0; i<arrElements.length; i++) {
        getEl(arrElements[i]).className = '';
    }
    getEl(newTarget).className = 'searchCatBg';


    return false;
}

function searchTarget2(url, newWindow, newTarget) {
    // Set the target for the form

    document.bb_bottomform.action = url;
    if (newWindow) {
        document.bb_bottomform.target = '_blank';
    } else {
        document.bb_bottomform.target = '';
    }
    // Update the tabs classes to allow highlighting of the selected
    var arrElements = ["search-tab-bot-1","search-tab-bot-2","search-tab-bot-3","search-tab-bot-4","search-tab-bot-5"];
    for (var i=0; i<arrElements.length; i++) {
        getEl(arrElements[i]).className = '';
    }
    getEl(newTarget).className = 'searchCatBg';


    return false;
}

function eventIsEnterKey(event) {
    if (event && event.which == 13 || window.event && window.event.keyCode == 13 || event && event.which == 3 || window.event && window.event.keyCode == 3) {
        return true;
    }
    return false;
}

function submitHeaderSearch(event) {
    if (event == "onclick" || eventIsEnterKey(event)) {
        return srchSub2();        
    } else {
        return true;
    }
}

function srchSub2() {
    var frm=p_o("search");
    var queryval = frm.topquery.value.trim();
    queryval = queryval.replace( /\+/, " ");
    var newurl = frm.action + URLEncode(queryval);
    if (frm.target == '_blank') {
        window.open(newurl, '_blank', '');
    } else {
        window.location = newurl;
    }
    return false;
}

function submitFooterSearch(event) {
    if (event == "onclick" || eventIsEnterKey(event)) {
        return srchSub4();        
    } else {
        return true;
    }
}

function srchSub4() {
    var frm=p_o("search2");
    var queryval = frm.Bottomquery.value.trim();
    queryval = queryval.replace( /\+/, " ");
    var newurl = frm.action + URLEncode(queryval);
    if (frm.target == '_blank') {
        window.open(newurl, '_blank', '');
    } else {
        window.location = newurl;
    }
    return false;
}



// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresearch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
// ====================================================================
function URLEncode(textToEncode)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = textToEncode;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for
	return encoded;
};

/*end header functions*/

function getEl( id ){ return document.getElementById( id ); }


function AsnsSignIn( obj, leftOffSet, topOffSet, ele ) {
  if (!leftOffSet) leftOffSet = 0;
  if (!topOffSet) topOffSet = 0;
  var pSNS = getEl(ele);
  pSNS.innerHTML = "";
  pSNS.innerHTML += _sns_var_;
  if ( document.all ) {
    var pos = findPos(obj);
    pSNS.style.position = 'absolute';
    pSNS.style.left = (pos[0] + leftOffSet - 138) + 'px';
    pSNS.style.top =  (pos[1] + topOffSet + 12)  + 'px';
  } else {
    obj.appendChild(pSNS);
    pSNS.style.left = leftOffSet + 'px';
    pSNS.style.top =  topOffSet  + 'px';
    pSNS.style.position = 'relative';
  }
  var close = document.createElement("span");
  var a = document.createElement("a");
  a.href = 'javascript:AsnsClose("'+ele+'")';
  a.title = "close";
  var img = document.createElement("img")
  img.src = "http://my.screenname.aol.com/images/10x10_x.gif";
  img.style.border = "0px"
  a.appendChild(img);
  close.appendChild(a);
  spans = pSNS.getElementsByTagName("span");
  spans[1].style.cssFloat = "right";
  spans[1].style.styleFloat = "right";
  spans[1].style.margin = "1px 0px 0px 10px";
  close.style.cssFloat = "right";
  close.style.styleFloat = "right";
  close.style.margin = "2px 2px 0px 0px";
  spanPar = spans[1].parentNode;
  spanPar.insertBefore(close,spans[1]);
  pSNS.style.zIndex = 5000;
  pSNS.style.display = "block";
}
function closeSNS(ele) {
  getEl(ele).innerHTML = '';
}

function AsnsClose(ele) {
  pSNS = getEl(ele);
  pSNS.style.display = "none";
}


function shareWin(url) {
    w = window.open(url,'holidaysShared','resizable=no,height=534,width=786');
    if (window.focus) {
        w.focus()
    }
    return false;
}

var promoDisplay = false;
function crossPromoDisplay() {
	var pos = $("#OnOurRadar").position();
	if (promoDisplay == false){
	if  ($(window).scrollTop() >= $(document).height() - parseInt(pos.top)){
		$("#cod-promo").load($("#OnOurRadar").find("a").attr("href"));
		promoDisplay = true;
	}
	}
}

function expandTextBox(){
var plength=(($("#searchBx").attr("value").length)-15)*5;
	if($("#searchBx").attr("value").length>15)
	    {
		$("#searchBx").css("width", eval(104+plength)+"px")
	}
}

/*Carousel  starts */
var gDefInx = 0;
var gSelInx;
var gAssetArr = new Array();

function loadCarousal() {
	gSelInx = gDefInx==0?1:gDefInx;
	for(i=0;i<gAssetArr.length;i++) {
		var liObj = document.createElement("li");
		liObj.innerHTML = "<a href='"+gAssetArr[i].aLnk+"' class='asset' title='"+gAssetArr[i].aName+"'><img src='' alt='"+gAssetArr[i].aName+"' /></a>";
		document.getElementById("assets").appendChild(liObj);
	}
	dispCurr();
	swapActv();
}

function loadCarousalSnag() {
	gSelInx = gDefInx==0?1:gDefInx;
	for(i=0;i<gAssetArr.length;i++) {
		var liObj = document.createElement("li");
		liObj.innerHTML = "<a href='"+gAssetArr[i].aLnk+"' class='asset' title='"+gAssetArr[i].aName+"'><img src='' alt='"+gAssetArr[i].aName+"' /></a>";
		document.getElementById("assets").appendChild(liObj);
	}
	dispCurrSnag();
	swapActvSnag();
}

function dispCurrSnag() {
	var liObj = document.getElementById("assets").getElementsByTagName("li");
	for(i=0;i<gAssetArr.length;i++) {
		if((gSelInx==0 && i== 2) || i==gSelInx-1 || i==gSelInx || i==gSelInx+1 || i==gSelInx+2) {
			liObj[i].style.opacity = 0;
			liObj[i].style.zoom = 1;
			liObj[i].style.filter = "alpha(opacity=0)";
			liObj[i].getElementsByTagName("img")[0].src = gAssetArr[i].aSrc;
			liObj[i].className = i==gDefInx?"show hl":"show";
			setTimeout("showAsset("+i+")",300);
		} else {
			liObj[i].className = "";
		}
	}
}

function dispCurr() {
	var liObj = document.getElementById("assets").getElementsByTagName("li");
	for(i=0;i<gAssetArr.length;i++) {
		if((gSelInx==0 && i== 2) || i==gSelInx-1 || i==gSelInx || i==gSelInx+1 ) {
			liObj[i].style.opacity = 0;
			liObj[i].style.zoom = 1;
			liObj[i].style.filter = "alpha(opacity=0)";
			liObj[i].getElementsByTagName("img")[0].src = gAssetArr[i].aSrc;
			liObj[i].className = i==gDefInx?"show hl":"show";
			setTimeout("showAsset("+i+")",300);
		} else {
			liObj[i].className = "";
		}
	}
}
function swapActv() {
	if(gSelInx<2) {
		document.getElementById("cPrev").innerHTML = "<a class='prevInv'>&nbsp;</a>";
	} else {
		document.getElementById("cPrev").innerHTML = "<a class='prev' href='javascript:prev();' onmouseover=\"this.className='prev prevHover'\" onmouseout=\"this.className='prev'\">&nbsp;</a>";
	}
	if(gSelInx>=gAssetArr.length-2 || gAssetArr.length <2) {
		document.getElementById("cNext").innerHTML = "<a class='nextInv'>&nbsp;</a>";
	} else {
		document.getElementById("cNext").innerHTML = "<a class='next' href='javascript:next();' onmouseover=\"this.className='next nextHover'\" onmouseout=\"this.className='next'\">&nbsp;</a>";
	}
}
function swapActvSnag() {
	if(gSelInx<2) {
		document.getElementById("cPrev").innerHTML = "<a class='prevInv'>&nbsp;</a>";
	} else {
		document.getElementById("cPrev").innerHTML = "<a class='prev' href='javascript:prevSnag();' onmouseover=\"this.className='prev prevHover'\" onmouseout=\"this.className='prev'\">&nbsp;</a>";
	}
	if(gSelInx>=gAssetArr.length-2 || gAssetArr.length <2) {
		document.getElementById("cNext").innerHTML = "<a class='nextInv'>&nbsp;</a>";
	} else {
		document.getElementById("cNext").innerHTML = "<a class='next' href='javascript:nextSnag();' onmouseover=\"this.className='next nextHover'\" onmouseout=\"this.className='next'\">&nbsp;</a>";
	}
}
function prev() {
	if(gSelInx<2) {
		return;
	}
	gSelInx = gSelInx<3?1:gSelInx-1;
	swapActv();
	dispCurr();
}
function next() {
	if(gSelInx==gAssetArr.length-2) {
		return;
	}
	gSelInx = gSelInx<gAssetArr.length-2?gSelInx+1:gAssetArr.length-2;
	swapActv();
	dispCurr();
}
function prevSnag() {
	if(gSelInx<2) {
		return;
	}
	gSelInx = gSelInx<4?1:gSelInx-1;
	swapActvSnag();
	dispCurrSnag();
}
function nextSnag() {
	if(gSelInx==gAssetArr.length-3) {
		return;
	}
	gSelInx = gSelInx<gAssetArr.length-3?gSelInx+1:gAssetArr.length-3;
	swapActvSnag();
	dispCurrSnag();
}
function showAsset(i) {
	var liObj = document.getElementById("assets").getElementsByTagName("li");
	if(liObj[i].style.opacity<.9) {
		liObj[i].style.opacity = eval(liObj[i].style.opacity)+.05;
		liObj[i].style.filter = "alpha(opacity="+(liObj[i].style.opacity*100)+")";
		setTimeout("showAsset("+i+")",50);
	} else {
		liObj[i].getElementsByTagName("img")[0].src = liObj[i].getElementsByTagName("img")[0].src;
	}
}
/*Carousel  ends */

/*IncrementPhotoAssetView starts*/
function incrementPhotoAssetView(categoryid,photourn,encphotouserguid,contextpath){
	var url=contextpath+'/incrementPhotoAssetView.jsp?categoryid='+categoryid+'&photourn='+photourn+'&encphotouserguid='+encphotouserguid;
	ajaxCall(url);
}
/*IncrementPhotoAssetView ends*/

/*incrementGalleryAssetView starts*/
function incrementGalleryAssetView(categoryid,galleryurn,encgalleryuserguid,contextpath){
	var url=contextpath+'/incrementGalleryAssetView.jsp?categoryid='+categoryid+'&galleryurn='+galleryurn+'&encgalleryuserguid='+encgalleryuserguid;
	ajaxCall(url);
}
/*incrementGalleryAssetView ends*/
/*share module starts*/
function shareWin(url) {
	w = window.open(url,'holidaysShared','resizable=yes,height=534,width=786');
	if (window.focus) {
		w.focus()
	}
	return false;
}
/*share module ends*/

/*snag copy starts*/
function copy(text2copy,contextpath) {
	if( document.getElementById("snagText")){
		document.getElementById("snagText").focus();
		document.getElementById("snagText").select();
	}
	if (window.clipboardData) {
		window.clipboardData.setData("Text",text2copy);
	} else {
	var flashcopier = 'flashcopier';
	if(!document.getElementById(flashcopier)) {
		var divholder = document.createElement('div');
		divholder.id = flashcopier;
		document.body.appendChild(divholder);
	}
	document.getElementById(flashcopier).innerHTML = '';
	var divinfo = '<embed src="'+contextpath+'/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	document.getElementById(flashcopier).innerHTML = divinfo;
	
	}
}
/*snag copy ends*/

function SubmitForm(filtertype, activepage, category){
	var srchFRM = document.browseResults;

	srchFRM.filtertype.value = filtertype;
	srchFRM.activepage.value = activepage;

	
	if ($("#browseGal").length)
		{
		srchFRM.action="/photos/"+ category +"/browse-galleries/"+srchFRM.subcategory.value;
		}
	else if($("#searchResults").length) 
		{
		srchFRM.action= "/photos/"+ category +"/search-results/"+srchFRM.searchterm.value;
		}
	else if($("#userGal").length)
		{
		srchFRM.action= "/photos/user-galleries/"+srchFRM.userName.value;
		} 
	else if($("#mngGal").length)
		{
		srchFRM.action= "/photos/manage-galleries/";
		} 
	else if($("#tagResults").length)
		{
		srchFRM.action= "/photos/"+ category +"/tag-search/"+srchFRM.tag.value+"?type="+srchFRM.type.value;
		} 
	else 
		{srchFRM.action="/photos/"+ category +"/browse-photos/"+srchFRM.subcategory.value;}
		srchFRM.submit();
}

function SubmitFormBottom(filtertype, activepage, category){
	var srchFRM = document.browseResults;
	srchFRM.numitemperpage.value=srchFRM.numitemperpage2.value;
	SubmitForm(filtertype, activepage, category);
}

function SubmitSearchForm(){
	var srchFRM = document.browseResults;
	if(srchFRM.searchterm.value.replace(/\s/g,"")==""){return;}
	srchFRM.type.value='photo';
	srchFRM.action='/photos/' + srchFRM.searchCategoryMain.value + '/search-results/'+srchFRM.searchterm.value;
	srchFRM.submit();
}
function SubmitLeftSearchForm(){
	var srchFRM = document.searchFrm;
	//alert(srchFRM.searchCategory.value);
	if(srchFRM.searchterm.value.replace(/\s/g,"")==""){return;}
	var srchCat = srchFRM.searchCategory.value;
	if(srchCat=="")srchCat=defaultCategoryFromBeSeol
	srchFRM.action='/photos/' + srchCat + '/search-results/'+srchFRM.searchterm.value;
	srchFRM.submit();
}
function doClear(theText){
	if (theText.value == theText.defaultValue){
		theText.value = "";
	}
}

/*left nav search submit start*/
function fn_submitSearchForm(){
	var searchBxValue=document.getElementById("searchBxLeft").value.trim();	
	if(searchBxValue!=null && searchBxValue!=''){	
		//alert(searchFromActionValueQueryString);
		document.searchFrm.action=searchFromActionValue+searchBxValue+searchFromActionValueQueryString;
		document.searchFrm.submit();
	}
	else
		return;
}
/*left nav search submit ends*/

function fn_miniSignIn(obj, parentUrl, sitedomain,contextPath){
    
    //if(obj) {		
	//alert ("anu: "+parentUrl+ " - "+sitedomain+" - "+contextPath)
    var parDiv = document.createElement("div");
    parDiv.style.position="absolute";
    parDiv.style.zIndex="100";
    parDiv.style.display="inline";
    parDiv.style.margin="22 -17";
    var innerHtml = ajaxCall(contextPath+"/miniSignInPopup.jsp?parentUrl="+encodeURL("http://home.aol.com"+contextPath+parentUrl)+"&sitedomain="+domainFromHard);
    //flgFly = obj.parentNode.rowIndex;
    parDiv.innerHTML= "<div id='snsMiniUI' style='left: -103px; top: -49px; position: relative; z-index: 5000; display: block;'>"+innerHtml+"</div>";
    obj.appendChild(parDiv);
    //}
    
}
function ajaxCall(url) {
	var page_request = false;
	if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
			}
		}
	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else
		return false
	page_request.open('GET', url, false) //get page synchronously
	page_request.send(null);
	return page_request.responseText;

	
}

function encodeURL (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
}

function decodeURL(utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

        c = utftext.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224)) {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }

    return string;
}

function cntCheckOfCommnts()
{
var	cnt=document.getElementById("commentsMaxLength");
var	field=document.getElementById("typcomnthere").value;
var len=field.length;
if(len > 1000){
	document.getElementById("typcomnthere").value=field.substring(0,1000);
	}
	else
	{
	cnt.innerHTML=1000-len+"/1000";
	}
}

function fn_notify(obj,channelURN,galleryId,photoURN,userName,userGUID,ipAddr,contextPath){				
	if(obj && document.getElementById("notPop") && obj.parentNode.rowIndex==flgFly) {return;}
	if(document.getElementById("notPop")){
		var x=document.getElementById("notPop").parentNode;
		x.parentNode.removeChild(x);
	}
	if(obj) {
		var parDiv = document.createElement("div");
		parDiv.style.position="absolute";		
		var innerHtml = ajaxCall(contextPath+"/reportAboutAsset.jsp/?channelURN="+channelURN+"&galleryURN="+galleryId+"&photoURN="+photoURN+"&userName="+userName+"&ipAddr="+ipAddr+"&contextPath="+contextPath+"&userGUID="+userGUID);
		flgFly = obj.parentNode.rowIndex;
		parDiv.innerHTML= '<div id="notPop"><a onclick="fn_notify();" class="closeBut">CLOSE</a><div class="notPMain">'+innerHtml+'</div></div>';
		obj.parentNode.insertBefore(parDiv,obj);
	}
}

//REPORT THIS TOP POP UP
function comment_report_popup(obj, coco, violator, clip, deleteInfo,contextPath){
    if(obj && document.getElementById("notPop") && obj.parentNode.rowIndex==flgFly) {return;}
    if(document.getElementById("notPop")){
            var x=document.getElementById("notPop").parentNode;
            x.parentNode.removeChild(x);
    }
    if(obj) {
            var parDiv = document.createElement("div");
            parDiv.style.position="absolute";
			parDiv.className = "reportParent";
            var innerHtml = ajaxCall(contextPath+"/commentReport.jsp?coco="+coco+"&violator="+violator+"&clip="+clip+"&dinfo="+deleteInfo+"&url="+document.location);
            flgFly = obj.parentNode.rowIndex;
            parDiv.innerHTML= '<div id="notPop"><a onclick="comment_report_popup()" class="closeBut">CLOSE</a><div class="notPMain">'+innerHtml+'</div></div>';
            obj.parentNode.insertBefore(parDiv,obj);
    }
}

//SUBMIT REPORT THIS FORM VIA POP UP
function reportThisComment(umtHost, coco, violator, clip, deleteInfo, contextPath,umtProduct) {

    var yourEmailAddr=document.getElementById("yourEmailAddr").value;
    if (yourEmailAddr == null) {
    	yourEmailAddr = 'living_null@aol.com';
    }
    var userComment=document.getElementById("additComments").value;
    var reportType=document.getElementById("reportType").value;
var comment = encodeURIComponent(userComment + "<br>Report Type: " + reportType);
    clip = encodeURIComponent(clip + "<br><br>" + deleteInfo);
    //umtHost = "http://qaccare-ql02.tops.aol.com:9180/umt/queued_add.jsp";
    //umtHost = "/lyratest.jsp";        
var reportAbuseData = "action=insert&reporter=" + yourEmailAddr + "&product="+umtProduct+"&violator=" + violator + "&coco=" + coco + "&violator_url=" + encodeURIComponent(document.location) + "&clip=" + clip  + "&comment=" + comment;

    http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                    // set type accordingly to anticipated content type
                    //http_request.overrideMimeType('text/xml');
                    http_request.overrideMimeType('text/html');
            }
    } else if (window.ActiveXObject) { // IE
            try {
                    http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                    try {
                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {}
            }
    }
    if (!http_request) {
            //alert('Cannot create XMLHTTP instance');
            return false;
    }
    
    http_request.open('POST', umtHost, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", reportAbuseData.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(reportAbuseData);
    comment_report_popup();
}
function reportThisCommentCancel() {
    //alert("test");
    comment_report_popup();
}

function reportThisNotify(channelURN,galleryId,photoURN,userName,userGUID,ipAddr,contextPath) {	
	//alert("test");
	var yourEmailAddr=document.getElementById("yourEmailAddr").value;
	var additComments=document.getElementById("additComments").value;
	var reportType=document.getElementById("reportType").value;
	var res=ajaxCall(contextPath+"/submitNotification.jsp?channelURN="+channelURN+"&galleryURN="+galleryId+"&photoURN="+photoURN+"&userName="+userName+"&userGUID="+userGUID+"&ipAddr="+ipAddr+"&yourEmailAddr="+yourEmailAddr+"&auditComments="+additComments+"&reportType="+reportType);
	javascript:fn_notify();
}
function reportThisNotifyCancel() {
	//alert("test");
	javascript:fn_notify();
}
function cntCheckOfCommntsInNotify()
{
	var	cnt=document.getElementById("notifyCommentsMaxLength");
	var	field=document.getElementById("additComments").value;
	var len=field.length;
	if(len > 1024){
		document.getElementById("additComments").value=field.substring(0,1024);
		cnt.innerText=0;
		cnt.innerHTML=0;
	}else{
	    cnt.innerText=1024-len;
	    cnt.innerHTML=1024-len;
	}
}
function middleGalleryModule(categoryid,innitial,itemstodisplay,noofgalleries,contextpath,galleryurn,category){
	var end;
	var start;
	if(parseInt(innitial)<parseInt(noofgalleries)/parseInt(itemstodisplay)){
		start=parseInt(innitial)*parseInt(itemstodisplay);
		innitial=parseInt(innitial)+1;
	}
	else{
	 	innitial=1;
		start=0;	
	}
	if((parseInt(start)+parseInt(itemstodisplay))<=parseInt(noofgalleries))
		end=parseInt(start)+parseInt(itemstodisplay);
	else
		end=noofgalleries;
		var url=contextpath+'/endCardGalleryView.jsp?categoryid='+categoryid+'&start='+start+'&end='+end+'&galleryurn='+galleryurn+'&category='+category;
		var eCard=ajaxCall(url);
		//alert(eCard);
		document.getElementById("middleModule").innerHTML=eCard;
		//var t=setTimeout('middleGalleryModule("'+categoryid+'","'+innitial+'","'+itemstodisplay+'","'+noofgalleries+'","'+contextpath+'","'+galleryurn+'","'+category+'")',7000);
	}
function middlePhotoModule(categoryid,innitial,itemstodisplay,catlistsize,contextpath){

	var end;
	var start;
	if(parseInt(innitial)<parseInt(catlistsize)/parseInt(itemstodisplay)){
		start=parseInt(innitial)*parseInt(itemstodisplay);
		innitial=parseInt(innitial)+1;
	}
	else{
	 	innitial=1;
		start=0;	
	}
	if((parseInt(start)+parseInt(itemstodisplay))<=parseInt(catlistsize))
		end=parseInt(start)+parseInt(itemstodisplay);
	else
		end=catlistsize;
		var url=contextpath+'/endCardPhotoView.jsp?categoryid='+categoryid+'&start='+start+'&end='+end;
		var eCard=ajaxCall(url);
		//alert(eCard);
		document.getElementById("middleModule").innerHTML=eCard;
		var t=setTimeout('middlePhotoModule("'+categoryid+'","'+innitial+'","'+itemstodisplay+'","'+catlistsize+'","'+contextpath+'")',7000);
}
String.prototype.trim = function() {  
	   return this.replace(/^\s+/,"").replace(/\s+$/,"");  
}  
function checkComment(){
	
	var browser=navigator.appName;
	
	var b_version=navigator.appVersion;
	
	var version=parseFloat(b_version);
	
   
    var commTxt=document.getElementById("typcomnthere").value.trim();
  
    if(commTxt=='Type Your Comment Here' || commTxt==null || commTxt=='') {
    	return;
    }
    else{
			
			document.commts.typcomnthere.value = document.commts.typcomnthere.value.replace(/\"/g,"");
			document.commts.typcomnthere.value = document.commts.typcomnthere.value.replace(/^\s*/, "").replace(/\s*$/, "").replace(/\\/g,"");
			/***** Firefox only needs this line *****/
			document.commts.typcomnthere.value=document.commts.typcomnthere.value.replace(/\n/g,' ');
			/***** IE and Opera need this line also *****/
            document.commts.typcomnthere.value=document.commts.typcomnthere.value.replace(/\s/g,' ').replace(/  ,/g,' '); 
        	document.commts.submit();
		              
    }
}
var ratingFlg = true; // If user login info available, change this to true else false
var usrRate = 0;
var isAvgFlag = 0;
var userRating = 0;
function galRate() {
	if(isAvgFlag==1){return;}
	var ratColl = document.getElementById("gRat").getElementsByTagName("a");
	var rateTemp = usrRate==0 && ratColl[0].parentNode.getAttribute("rating")>0?ratColl[0].parentNode.getAttribute("rating"):usrRate;
	for(i=0;i<ratColl.length;i++) {
		ratColl[i].className = i<Math.floor(rateTemp)?"backPicFill":"backPicEmpty";
		if(rateTemp>i&&rateTemp<(i+1)&&rateTemp-i>.4) {
			ratColl[i].className = "backPicHalf";
		}
	}
}
function galRateIt(obj,assetURN,catId,userGUID,assetType,contextpath)
{
	//alert("radha");
	//if(!ratingFlg) {return;}
	if(userRating==1){return;}
	usrRate = obj.id.replace("star","");
        //alert("gallery: " + galleryId + "catId: " + catId + "userGUID: " + userGUID);
	ajaxCall(contextpath+"/rateIt.jsp?newRating="+usrRate+"&assetURN="+assetURN+"&categoryID="+catId+"&userGUID="+userGUID+"&assetType="+assetType);
	//ratingFlg = false;
	yourRating=usrRate;
	userRating=1;
}
function galRatingIn(obj)
{	
	//alert(userRating);
	//alert(isAvgFlag);
	if(isAvgFlag==1){return;}
	if(userRating==1){return;}
	//if(!ratingFlg) {return;}
	var ratColl = document.getElementById("gRat").getElementsByTagName("a");
	for(i=0;i<ratColl.length;i++) {
		ratColl[i].className = i<obj.id.replace("backPicEmpty","")?"backfillash":"backPicEmpty";
	}
	//userRating=1;
}
function galChRate(obj,aStr,rating,pgName)
{	
	var ratColl = document.getElementById("gRat").getElementsByTagName("a");	
	for(i=0;i<ratColl.length;i++) {
		ratColl[i].className = i<Math.floor(rating)?"backPicFill":"backPicEmpty";
		if(rating>i&&rating<(i+1)&&rating-i>.4) {
			ratColl[i].className = "backPicHalf";
			//i++;
		}
	}
	if(aStr=="Average Rating"){
		obj.parentNode.innerHTML = "<span  onclick=\"javascript:galChRate(this,'Your Rating',"+avgRating+",'"+pgName+"');\" style=\"color:#3094C6;cursor:pointer;\">Avg Rating </span>";
		document.getElementById("ratingTitle").innerHTML="Your Rating";
		isAvgFlag=0;
	}
	else{
		obj.parentNode.innerHTML = "<span  onclick=\"javascript:galChRate(this,'Average Rating',"+yourRating+",'"+pgName+"');\" style=\"color:#3094C6;cursor:pointer;\">Your Rating </span>";
		if(pgName=="gallery")
			document.getElementById("ratingTitle").innerHTML="Avg Rating";
		else
			document.getElementById("ratingTitle").innerHTML="Avg Rating";
		isAvgFlag=1;
	}
	galRate();
}
function clearTxtArea()
{
	document.getElementById("typcomnthere").value="";
	document.getElementById("commentsMaxLength").innerHTML="1000";
}


//ENLARGE IMAGE 
function enlargePic1()
{
var enURL=document.getElementById("enlargeURL").value;
var enDiv = document.createElement("div");
//enDiv.id="outerEnDiv";
enDiv.setAttribute('id','outerEnDiv');
enDiv.setAttribute('style',"height:"+document.height+"px");
var enInDiv = document.createElement("div");
//enInDiv.id="inEnDiv";
enInDiv.setAttribute('id','inEnDiv');
enInDiv.innerHTML="";
enInDiv.innerHTML += "<a href='javascript:void(0);' onclick='javascript:clBtn(this)' id='clBtn'>Close</a>";
var imgTag = document.createElement("img");
imgTag.setAttribute('class',"enImg");
imgTag.setAttribute('src',enURL);
document.body.appendChild(enDiv);
document.body.appendChild(enInDiv);
var t=enInDiv.appendChild(imgTag);

var iFrame= document.createElement("iframe");
iFrame.setAttribute('src','/photos/enlarge_ad.jsp');
iFrame.setAttribute('id','iFrm');
iFrame.setAttribute('frameBorder','0');
iFrame.setAttribute('allowTransparency','true');
enInDiv.appendChild(iFrame);
enInDiv.innerHTML += '<div class="clear"></div>';
window.scrollTo(0,0);
}

function enlargePic()
{
	setTimeout('enlargePic1()',1000);
}
function clBtn(obj)
{
	if(obj && document.getElementById("outerEnDiv") && obj.parentNode.rowIndex==flgFly) {return;}
	if(document.getElementById("outerEnDiv") && document.getElementById("inEnDiv")){
	var x=document.getElementById("outerEnDiv");
	x.parentNode.removeChild(x);
	var x=document.getElementById("inEnDiv");
	x.parentNode.removeChild(x);
	}
}

//Search Header Functions
function togMore(sShow){
	if (sShow == "hide"){
		$(".smore").css({'display' : 'none'});
		}else{
		$(".smore").css({'display' : 'block'});
	}
	return false;
}

/*Tog Photos Functions
function togPhotos(sShow){
	if (sShow == "hide"){
		$(".smore_photos").css({'display' : 'none'});
		}else{
		$(".smore_photos").css({'display' : 'block'});
	}
	return false;
}*/

 function srchSub(ref){
	  var queryval = jQuery.trim($(".searchFld").val());
	  queryval = queryval.replace( /\+/, " ");
	  newurl = ref.href + queryval;
	  window.location = newurl;
	}

//Manage Gallery Functions
function deleteGallery(obj)
{
	var galID = obj.getAttribute("id").split("_")
	if(confirm("Do you want to delete this gallery?")) {
		galId="/photos/deleteGallery.jsp?gallery="+galID[1];
		var stat=ajaxCall(galId);
		//alert(stat);
		if (stat==0){
			obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
			document.getElementById("gCount").innerHTML=eval(document.getElementById("gCount").innerHTML)-1;
		} else {
			//alert("Try after some time.");
			window.location.reload();
		}
	}
}	

var flgFly = "";
function fn_addItem(obj,msg) {
	if(obj && document.getElementById("popupQuestionMark") && obj.parentNode.rowIndex==flgFly) {return;}

	if(document.getElementById("popupQuestionMark")){
		var x=document.getElementById("popupQuestionMark").parentNode;
		x.parentNode.removeChild(x);

	}
	if(obj) {
		var parDiv = document.createElement("div");
		parDiv.style.position="absolute";
		parDiv.style.zIndex="100";
		parDiv.style.display="inline";
        parDiv.style.margin="27px 10px";
		var innerHtml = ajaxCall("/photos/popupQuestion.jsp?msg="+msg);
		flgFly = obj.parentNode.rowIndex;
		parDiv.innerHTML= "<div id='popupQuestionMark'><a href='javascript:void(0);' onclick='javascript:fn_addItem();'>&nbsp;</a><div class='popupContentPart'>"+innerHtml+"</div></div>";
	obj.parentNode.insertBefore(parDiv,obj);
	}
}

function fn_addItemManage(obj,msg) {
	if(obj && document.getElementById("popupQuestionMark") && obj.parentNode.rowIndex==flgFly) {return;}

	if(document.getElementById("popupQuestionMark")){
		var x=document.getElementById("popupQuestionMark").parentNode;
		x.parentNode.removeChild(x);

	}
	if(obj) {
		var parDiv = document.createElement("div");
		parDiv.style.position="absolute";
		parDiv.style.zIndex="100";
		parDiv.style.display="inline";
        parDiv.style.margin="27px 10px";
		var innerHtml = ajaxCall("/photos/popupQuestion.jsp?msg="+msg);
		flgFly = obj.parentNode.rowIndex;
		parDiv.innerHTML= "<div id='popupQuestionMark'><a href='javascript:void(0);' onclick='javascript:fn_addItem();'>&nbsp;</a><div class='popupContentPart'>"+innerHtml+"</div></div>";
	obj.parentNode.insertBefore(parDiv,obj);
	}
}

// Share Javascript
function submitReq() {
    if (document.forms[0].emailTo.value =='' || document.forms[0].emailMsg.value =='') {
        alert('To and Message fields are required.');
        return;
    }
    var emailMsg = document.forms[0].emailMsg.value +"\n"+document.forms[0].emailUrl.value;
    var emailTo = document.forms[0].emailTo.value;                
    var emailFrom = document.forms[0].emailFrom.value;
    var emailSubject = document.forms[0].emailSubject.value;
    makeRequest('/photos/ajax_handlers/sendEmail.jsp?emailMsg=' + escape(emailMsg) + '&emailFrom=' + escape(emailFrom)+ '&emailTo=' + escape(emailTo)+ '&emailSubject=' + escape(emailSubject));
}

var request = false;

function makeRequest(url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
    request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.open('POST', url, true);
    request.onreadystatechange = reqStatus;
    request.send(url);
}

function sendDisabled(val,btnId) {
    if (val == 1) {
        document.getElementById(btnId).disabled=true;  
    }
    if (val == 0) {
       document.getElementById(btnId).disabled=false;  
    }                
}

function reqStatus() {
    if (request.readyState == 4) {
        if (request.status == 200) {                         
            if (request.responseText == 1) {
                document.getElementById('formMsg').innerHTML = 'Message Successful' ;
                sendDisabled(1,'sendauth');
            } else {
            document.getElementById('formMsg').innerHTML = 'There was a problem with the request.';
            sendDisabled(1,'sendauth');
            }
        } else {              
        document.getElementById('formMsg').innerHTML = 'There was a problem with the request.';
        sendDisabled(1,'sendauth');
        }
    }
}

function onFieldFocus(id,msg) {
    if(document.getElementById(id).value == msg){
        document.getElementById(id).value = ''; 
    }
}

function onFieldBlur(id,msg) {
    if(document.getElementById(id).value == ''){
        document.getElementById(id).value = msg; 
    }
}
// End of Share Javascript
//jquery ready event
$(document).ready(function(){
	
	//authentication method call for sign in button
	if ($("#userspan").length){
		loginCheck(domainFromHard);
	}
	
	// removes left/right buttons if carousal does not have enough items
	if ($("#carousal ul li").length){
		var width = $("#carousal ul").css("width").split('px')
		if ($("#carousal ul li").length <= Math.floor(width[0]/78)){
			$("#carousal #cPrev, #carousal #cNext").css({'display':'none'});
		}
	}
	
	// on load test cross promo position
	if ($("#cod-promo").length){
		crossPromoDisplay();
	}
	if ($("#searchBx").attr("value") != null){expandTextBox();}
	//Hover action for browse Galleries
	
	$(".galCell").bind("mouseover", function() {
		$(this).addClass("active");
	});
	$(".galCell").bind("mouseout", function() {
		$(this).removeClass("active");
	});
	//  Report this help function
	$("#rptMoreInfo").bind("mouseover", function() {fn_addItem(this,6);});
	$("#rptMoreInfo").bind("mouseout", function() {fn_addItem();});
	
	$("#questionBubbleImg").bind("mouseover", function() {fn_addItem(this,4);});
	$("#questionBubbleImg").bind("mouseout", function() {fn_addItem();});
	
	// search field
	$("#searchBx").bind("focus", function(){doClear(this)});
	$("#searchBx").bind("click", function(){$(this).css("color", "#373737")});
	
	// comment text area
	$("#typcomnthere").bind("focus", function(){doClear(this)});
	
	// search form on return key
	$("#searchBx").keypress(function (e) {
		if(e.which == '13'){
			SubmitSearchForm();
		}
	});
	
	// Search left nav
	$("#searchBxLeft").keypress(function (e) {
		if(e.which == '13'){
			SubmitLeftSearchForm();
		}
	});
	// header search tabs
	$(".search-tab-Web a, .search-tab-Images a, .search-tab-Video a, .search-tab-News a, .search-tab-Local a").bind("click", function(){ 
		// Set the target for the form
		$(".search").attr("action", $(this).attr("href"));
		$(".search").attr("target", "_blank");
	    $(".searchCat ul li").removeClass("searchCatBg");
	    $(this).parent("li").addClass("searchCatBg");
	    return false;
	});
	
	$(".smorea").bind("click", function(){
		togMore('show');
	});
	$(".smorex").bind("click", function(){
		togMore('hide');
	});
	$(".om_srchmore a").bind("click", function(){
		 srchSub(this);
		 return false;
	});
	
	
	/*$(".smorea_photos").bind("mouseenter", function(){
		togPhotos('show');
	});
	$(".smore_photos").bind("mouseenter", function(){
		togPhotos('show');
	});
	$(".smorea_photos").bind("mouseleave", function(){
		togPhotos('hide');
	});
	$(".smore_photos").bind("mouseleave", function(){
		togPhotos('hide');
	});
	*/
	
	$(".om_srchmore_photos a").bind("click", function(){
		 srchSub(this);
		 return false;
	});
	
	
	$(".gDelete").bind("click", function(){
		deleteGallery(this);
	});
	
	$(window).scroll(function () { 
		// on scroll test cross promo position
		if ($("#cod-promo").length){
			crossPromoDisplay();
		}
	});
});

function galRateItAs(obj,assetURN,catId,userGUID,assetType,contextpath)
{

	//alert("radha");
	//if(!ratingFlg) {return;}
	if(userRating==1){return;}
	usrRate = obj.id.replace("star","");
        //alert("gallery: " + galleryId + "catId: " + catId + "userGUID: " + userGUID);
	ajaxCall(contextpath+"/rateIt.jsp?rating="+usrRate+"&assetURN="+assetURN+"&categoryID="+catId+"&userGUID="+userGUID+"&assetType="+assetType);
	//ratingFlg = false;
	yourRating=usrRate;
	userRating=1;
}

//Share Javascript
function submitEmail() {
	
    if (document.authform.emailMsg.value == 'Enter your personal message here.') {
    	document.authform.emailMsg.value = '';
    }
	
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var emailMsg = document.authform.emailMsg.value + "\n\n===========================================================\nBrought to you by AOL:\n<"+document.authform.emailUrl.value+">\nSecurity: You should not be asked to sign-in, after clicking on the above link.\n\n===========================================================\n\n";    
    var emailTo = document.authform.emailTo.value;                
    var emailFrom = document.authform.emailFrom.value;
    var emailSubject = document.authform.emailSubject.value;

    if(reg.test(emailTo) == false) {
        alert('Invalid Recepient Email Address');
        return false;
    }
    if(reg.test(emailFrom) == false) {
        alert('Invalid Sender Email Address');
        return false;
    }

    makeRequest('/photos/ajax_handlers/sendEmail.jsp?emailMsg=' + escape(emailMsg) + '&emailFrom=' + escape(emailFrom)+ '&emailTo=' + escape(emailTo)+ '&emailSubject=' + escape(emailSubject));
}
/* Browse Video in Right Rail */
var timeOut, currCount, prevCount, galleryTotal;

function changePhoto(direction){
	//unbind button
	$(".next").unbind("click");
	$(".prev").unbind("click");
	
	$(".videoBrowse .imgGroup .img").eq(currCount).fadeOut("fast", function(){
		$(".videoBrowse ul li").eq(currCount).removeClass("highlight");	
		 if(direction == "prev"){
		    	currCount--;
		    	if(currCount < 0){currCount = galleryTotal-1;}
		      } else{
		    	  currCount++;
		    	  if(currCount > galleryTotal-1){currCount = 0;}
		      }
		$(".videoBrowse ul li").eq(currCount).addClass("highlight");
		$(".videoBrowse .imgGroup .img").eq(currCount).fadeIn("fast");
		// Bind buttons again
		$(".next").bind("click", function() {
			clearTimeout(timeOut);
			changePhoto('next');
		});
		$(".prev").bind("click", function() {
			clearTimeout(timeOut);
			changePhoto('prev');
		});	
		
	});
}

function noImage(){
	$(this).attr("src", "http://o.aolcdn.com/art/ch_home/gardening/images/profilepic-default.gif");
}


$(document).ready(function(){

	/* Browse Video in right rail */
	if ($(".videoBrowse").length){
		galleryTotal = $(".videoBrowse .imgGroup .img").length
		currCount =0;
		timeOut = setInterval(changePhoto, 6000);
	}
	$(".next").bind("click", function() {
		clearTimeout(timeOut);
		changePhoto('next');
	});
	$(".prev").bind("click", function() {
		clearTimeout(timeOut);
		changePhoto('prev');
	});
	$(".recentComments .commentUser img").bind("error", function() {
		noImage();
	});
	if ($(".managePreview").length){
		$(".managePreview").bind("click", function(){ managePreviewGallery(); });
	}

});
//begin HP Tabblo code
function __TABBLO_TPT_LOAD() {
    Tabblo.embedded.sites.SettingsObject.preprocess.apply({

        Properties:
        {
            template: 'news_large'
        },
        FixedContent:
        {
            accentcolor: '#741037',
            accentcolor2: '#b08431'
        },
        // content definition:
        Content:
        {
            'pagetitle':   { match: 'css', selector:'.articleTitle' },
            'text':        { match: 'css', selector:'#articleBody' },
            'logo':        { match: 'match',  attr: 'src', value:'aolhome_logo', continueHooks: false, nodeContentType: 'image' }                       
        }
    },[]);
    Tabblo.embedded.printabulous();
}

function MakePDF() {
    // append tabblo print script on demand
    var _tpt_script_loaded = false;
    if (!_tpt_script_loaded) {
	_tpt_script_loaded = true;
    	var tpS = document.createElement('script');
    	tpS.setAttribute('type','text/javascript');
    	tpS.setAttribute('charset', 'utf-8');
    	tpS.setAttribute('src','http://h30405.www3.hp.com/edit/tptboot/1.0');
    	document.getElementsByTagName('body').item(0).appendChild(tpS);
    } else {
	Tabblo.embedded.detect.setup(Tabblo.embedded.printabulous.bind(null,false));
    }
}
//end HP Tabblo code


var flgFly = "";
function fn_addItem(obj,msg) {
	if(obj && document.getElementById("popupQuestionMark") && obj.parentNode.rowIndex==flgFly) {return;}

	if(document.getElementById("popupQuestionMark")){
		var x=document.getElementById("popupQuestionMark").parentNode;
		x.parentNode.removeChild(x);

	}
	if(obj) {
		var parDiv = document.createElement("div");
		parDiv.style.position="absolute";
		parDiv.style.zIndex="100";
		parDiv.style.display="inline";
        parDiv.style.margin="27px 10px";
		var innerHtml = ajaxCall("/photos/popupQuestion.jsp?msg="+msg);
		flgFly = obj.parentNode.rowIndex;
		parDiv.innerHTML= "<div id='popupQuestionMark'><a href='javascript:void(0);' onclick='javascript:fn_addItem();'>&nbsp;</a><div class='popupContentPart'>"+innerHtml+"</div></div>";
	obj.parentNode.insertBefore(parDiv,obj);
	}
}


function changeSubCatE(path)
{
 var cat=document.desPho.category.value;
 var catType=document.desPho.catType.value;

url= path+"/changeSubCategory.jsp?sCat="+cat+"&catType="+catType;
var page_request = false;
	if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
			}
		}
	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else
		return false
	page_request.open('GET',url, false) //get page synchronously
	page_request.send(null);
	document.getElementById("subCatg").innerHTML=page_request.responseText;
	return page_request.responseText;

//ajaxCall1("subcat.jsp?sCat="+cat);
}

function frmEPublish(path)
{
	document.desPho.galleryTitle.value = document.desPho.galleryTitle.value.replace(/\"/g,"");
	document.desPho.galleryTitle.value = document.desPho.galleryTitle.value.replace(/^\s*/, "").replace(/\s*$/, "").replace(/\\/g,"");
	document.desPho.galleryTags.value = document.desPho.galleryTags.value.replace(/\"/g,"").replace(/\\/g,"");
	
	if(document.desPho.cnt.value==0)
	{
	alert("No Photos!! Please click on Add More Photos!!")
	}
	else if(document.desPho.galleryTitle.value.length==0)
	{
	document.getElementById("tError").style.display="block";
	document.getElementById("sError").style.display="none";
	document.getElementById("cError").style.display="none";
	return;
	}
	else if(document.getElementById("galTid").value.length>25){
	document.getElementById("sError").style.display="block";
	document.getElementById("tError").style.display="none";
	document.getElementById("cError").style.display="none";
	return;
	}
	else if(document.desPho.category.value.length==0)
	{
	document.getElementById("sError").style.display="none";
	document.getElementById("tError").style.display="none";
	document.getElementById("cError").style.display="block";
	return;
	}
	else
	{
	document.desPho.action = path+"/photos/preview-gallery/?gallery="+document.desPho.gallery.value+"&position=0";
	document.desPho.submit();
	} 
}

function updateOrder()
{
		for(i=0;i<document.getElementById("photoList").getElementsByTagName("label").length-1;i++){
			document.getElementById("photoList").getElementsByTagName("label")[i].innerHTML = i+1;
			document.getElementById("pOrder"+document.getElementById("photoList").getElementsByTagName("label")[i].parentNode.getElementsByTagName("textarea")[0].name.replace("caption","")).value = i+1;
		}
}

function delEditPhoto(pUrn,gallery)
{
		if(confirm("Do you want to delete this Photo?")) {

		galDet="/photos/deletePhoto.jsp?pUrn="+pUrn+"&gallery="+gallery;
		var stat=ajaxCall(galDet);
		if (stat==0){
			alert("Try after some time.");
		} else {
			window.location.reload();
		}
		}

}

function checkDescPhtoTitleLen(){	
	var	field=document.getElementById("txtPhotoTitle").value;
	var len=field.length;
	if(len > 25){
		document.getElementById("txtPhotoTitle").value=field.substring(0,25);
		}
}

function chkBlur(obj,val)
{
	var inst=obj.value;
	if(inst.indexOf("Enter photo") > -1 || inst.indexOf("Label with descriptive") > -1)
	{
		obj.style.color="#373737";
		obj.value="";
	}
 else
	{
   obj.style.color="#373737";
	}
}

function chkField(obj,val)
{
	if(obj.value.replace(/\s/g,"")=="" || obj.value.length < 0)
	{
		obj.value=val;
		obj.style.color="#B8B8B8";
	}
}

function cntCheck(num)
{
var	cntid="chCount"+num;
var	cnt=document.getElementById(cntid);
var field=eval("document.desPho.caption"+num).value;
var len=field.length;
cnt.style.display="inline";
if(len > 500){
	eval("document.desPho.caption"+num).value=field.substring(0,500);
	}
	else
	{
	cnt.innerHTML=500-len;
	}
}

function saveForLater(path)
{
	document.desPho.action = path+"/save-later";
	document.desPho.submit();
}

function requestParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function submitThisForm(sform,galId)
{
	var url="/photos" + sform.urlCat.value + "/upload-photos" + sform.urlSubCat.value + "?id=" +galId;

    sform.action=url;
	sform.submit();
}


var previewDataArray = new Array();
function buildPreviewArray() {
		previewDataArray = new Array(); 
		
		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		// + Let's populate the 'multidimensional' array          +
		// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		for (i = 0;i < 5; i++) {
	
		    previewDataArray.push(["photo" +i +"title","http://dpm-ln47.websys.aol.com:8781/images/5b424034366639356661631239157018_s1.jpg", "cap" + i, "tag "+i]);
	
		}
alert("out");
}
function previewManageGallery(){
 buildPreviewArray();
alert('in');

	var title = 0;
	var url = 1;
	var caption = 2;
	var tags = 3;
	var numPhotos = 5;
	var p_galTitle = "Gallery title";
	alert('in01');

	
	$("#previewPhotoView h4").text(p_galTitle+" ("+numPhotos+")");
alert('in4');
	$("#previewPhotoView span.photoCounter").html("Photo <span class=\"currentPreviewPhoto\">1</span> of "+numPhotos);
	$("#previewPhotoView a.prevButton").addClass("inactive");
	alert('in5');
	var firstImgSrc = (previewDataArray[i][url]).replace(/_s1/, "_s3");
	$("#previewPhotoView img").attr("src", firstImgSrc);
	
	$("#previewPhotoView h6").text(previewDataArray[i][title]);
	
	$("#previewPhotoView .photoTagline .tagUserId").text(_sns_current_user);
	//apply user galleries link to href
	$("#previewPhotoView .photoTagline .tagGalleryTitle").text(p_galTitle);
	//apply gallery url to href
	alert(previewDataArray[0][caption]);
	$("#previewPhotoView p").text(previewDataArray[0][caption]);
	
	$("#previewCarousel").html("<ul></ul>");
	var ulWidth = (numPhotos * 88)+4;
	$("#previewCarousel ul").css("width", ulWidth);
	carouselLeftMargin = 0;
	$("#previewCarousel ul").css("margin-left", carouselLeftMargin+"px");
	var activeClass = "";
	alert(previewDataArray[0][url]);
	for(var i=0;i<numPhotos;i++){alert(previewDataArray[i][url]);
		if(i==0){ activeClass = " active"; } else { activeClass = ""; }
		$("#previewCarousel ul").append("<li><img class=\""+i+activeClass+"\" height=\"78\" width=\"78\" src=\""+previewDataArray[i][url]+"\" alt=\""+previewDataArray[i][title]+"\"/></li>");
	}
	
	$(".carouselPrev").bind("click", function(){ carouselPrev(); });
	$(".carouselNext").bind("click", function(){ carouselNext(); });
	
	$("#previewCarousel ul li img").bind("click", function(){ changeMainPreviewImg(this); });
	
	tb_show('', '#TB_inline?height=600&width=520&inlineId=previewDialog&modal=true');
}

function frmPublishGal(path)
{
	if(document.desPho.cnt.value==0)
	{
	alert("No Photos!! Please click on Add More Photos!!")
	}else{

	document.desPho.action = path+"/publish-gallery";
	document.desPho.submit();
	}
}

/*
 * initialize gallery vars as empty, if gallery subcategory & gallery tags aren't default or empty, use them.
 * populate "galleryData" array within JSON object with gallery metadata from form
 * accepts 'encoded' param for save/publish and '' for preview.
 *
 * in for loop for building "photoData" array within the JSON object, we reset variables for each iteration,
 * assign current panel ID attribute to i_Id, use photo title, photo caption, and photo tags values if not default or empty,
 * then append the JSON with each individual photo's data set.
 * finally, we separate individual photo data sets with a comma, but leave it off of the last one.
 */
function manageConstructGalleryJSON(action){

  var g_GallerySubcategory = "";
  var g_GalleryTags = "";

  if($("#gallerySubcategory").val() != gallerySubcategoryDefault && $("#gallerySubcategory").val() != ""){
		g_GallerySubcategory = $("#gallerySubcategory").val();
  }

  if($("#galleryTags").val() != galleryTagsDefault && $("#galleryTags").val() != ""){
		g_GalleryTags = $("#galleryTags").val();
  }
	  galleryJSONString = "{'galleryData':[{'galleryTitle':'"+escape($("#galleryTitle").val())+"',";
	  galleryJSONString +=  "'galleryCategory':'"+escape($("#galleryCategory").val())+"',";
	  galleryJSONString += 	"'gallerySubcategory':'"+escape(g_GallerySubcategory)+"',";
	  galleryJSONString +=  "'galleryTags':'"+escape(g_GalleryTags)+"',";
	  galleryJSONString +=  "'galleryURN':'"+$.trim(galleryURN)+"'}],";
	  galleryJSONString +=  "'photoData':[";

  for(i=0;i<$(".phtoUpload").length;i++){
		if(!$(".phtoUpload").eq(i).hasClass("fileError") && !$(".phtoUpload").eq(i).hasClass("fileDeleted")){
			var i_PhotoTitle = "";
			var i_PhotoCaption = "";
			var i_PhotoTags = "";
			var i_PhotoURL = "";
			var i_PhotoURN = $(".photoURN").eq(i).val();

			if($(".photoTitle").eq(i).val() != photoTitleDefault && $(".photoTitle").eq(i).val() != ""){
				i_PhotoTitle = $(".photoTitle").eq(i).val();
			}
	
			if($(".photoCaption").eq(i).val() != photoCaptionDefault && $(".photoCaption").eq(i).val() != ""){
				i_PhotoCaption = $(".photoCaption").eq(i).val();
			}
	
			if($(".photoTags").eq(i).val() != photoTagsDefault && $(".photoTags").eq(i).val() != ""){
				i_PhotoTags = $(".photoTags").eq(i).val();
			}
			
			i_PhotoURL = $(".phtoUploadImgDelBtn img").eq(i).attr("src");

			if(action == "publish"){
				galleryJSONString +=  "{'photoTitle':'"+escape(i_PhotoTitle)+"',";
				galleryJSONString +=  "'photoCaption':'"+escape(i_PhotoCaption)+"',";
				galleryJSONString +=  "'photoTags':'"+escape(i_PhotoTags)+"',";
				galleryJSONString +=  "'photoURN':'"+$.trim(i_PhotoURN)+"'}";
			} else if(action == "preview"){
				galleryJSONString +=  "{'photoTitle':'"+escape(i_PhotoTitle)+"',";
				galleryJSONString +=  "'photoCaption':'"+escape(i_PhotoCaption)+"',";
				galleryJSONString +=  "'photoURL':'"+i_PhotoURL+"',";
				galleryJSONString +=  "'photoURN':'"+$.trim(i_PhotoURN)+"'}";
			}

			if(i!=($(".photoPanel").length-1)){
				galleryJSONString +=",";
			}
		}
  }

  galleryJSONString +=  "]}";
  
}

function managePreviewGallery(){
	manageConstructGalleryJSON("preview");
		if(previewJSON.length > 0){ previewJSON.length = 0; }
	var previewJSONString = galleryJSONString.replace(/'/g, "\"");
	previewJSON = JSON.parse(previewJSONString);

	var numPhotos = previewJSON.photoData.length;
	
	if(previewJSON.galleryData[0].galleryTitle == galleryTitleDefault || previewJSON.galleryData[0].galleryTitle == ""){
		var p_galTitle = "No Gallery Title";
	} else {
		var p_galTitle = unescape(previewJSON.galleryData[0].galleryTitle);
	}
	$("#previewPhotoView h4").text(p_galTitle+" ("+numPhotos+")");
	
	$("#previewPhotoView span.photoCounter").html("Photo <span class=\"currentPreviewPhoto\">1</span> of "+numPhotos);
	$("#previewPhotoView a.prevButton").addClass("inactive");
	
	var firstImgSrc = previewJSON.photoData[0].photoURL.replace(/_s1/, "_s3");
	$("#previewPhotoView img").attr("src", firstImgSrc);
	
	$("#previewPhotoView h6").text(unescape(previewJSON.photoData[0].photoTitle));
	
	$("#previewPhotoView .photoTagline .tagUserId").text(_sns_current_user);
	$("#previewPhotoView .photoTagline .tagUserId").attr("href", "/photos/user-galleries/"+sns_userguid);
	$("#previewPhotoView .photoTagline .tagGalleryTitle").text(p_galTitle);
	var p_galleryIDArr = previewJSON.galleryData[0].galleryURN.split(":");
	var p_galleryID = p_galleryIDArr[4];
	$("#previewPhotoView .photoTagline .tagGalleryTitle").attr("href", "/photos/"+$("#galleryCategory").val()+"/view-gallery/"+p_galleryID);
	
	$("#previewPhotoView p").text(unescape(previewJSON.photoData[0].photoCaption));
	
	$("#previewCarousel").html("<ul></ul>");
	var ulWidth = (numPhotos * 88)+4;
	$("#previewCarousel ul").css("width", ulWidth);
	carouselLeftMargin = 0;
	$("#previewCarousel ul").css("margin-left", carouselLeftMargin+"px");
	var activeClass = "";
	for(var i=0;i<numPhotos;i++){
		if(i==0){ activeClass = " active"; } else { activeClass = ""; }
		$("#previewCarousel ul").append("<li><img class=\""+i+activeClass+"\" height=\"78\" width=\"78\" src=\""+previewJSON.photoData[i].photoURL+"\" alt=\""+unescape(previewJSON.photoData[i].photoTitle)+"\"/></li>");
	}
	
	$(".carouselPrev").bind("click", function(){ carouselPrev(); });
	$(".carouselNext").bind("click", function(){ carouselNext(); });
	
	$("#previewCarousel ul li img").bind("click", function(){ changeMainPreviewImg(this); });
	
	tbWrappedPop(600, 520, "previewDialog", "true");
}

